如何在 MySQL 中将自动增量格式设置为 0001?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/611340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:52:30  来源:igfitidea点击:

How can I set autoincrement format to 0001 in MySQL?

mysql

提问by 32.

How can I make MySQL auto increment in 4 digit format?

如何使 MySQL 以 4 位格式自动递增?

So instead of '1' make '0001'?

所以不是'1'而是'0001'?

回答by Jeremy L

Try adding ZEROFILL attribute to the field.

尝试将 ZEROFILL 属性添加到该字段。

回答by Paul Dixon

Could you leave it as an integer and format it for humans in your SQL, for example, to pad with zeros to 4 chars wide

您能否将其保留为整数并在您的 SQL 中为人类设置格式,例如,用零填充到 4 个字符宽

select lpad(idcolumn,4,'0') from mytable;

Or use zerofill and specify the desired width when declaring the table:

或者在声明表格时使用 zerofill 并指定所需的宽度:

create table tmpfoo (
   mykey int(6) zerofill not null auto_increment, 
   primary key(mykey)
);

insert into tmpfoo values(1),(2);

select * from tmpfoo;
+--------+
| mykey  |
+--------+
| 000001 |
| 000002 |
+--------+

回答by gahooa

MySQL supports ZEROFILLon integer columns:

MySQL在整数列上支持 ZEROFILL

mysql> create table foo (the_key int unsigned zerofill not null 
       auto_increment primary key);
Query OK, 0 rows affected (0.21 sec)

mysql> insert into foo SET the_key = Null;
Query OK, 1 row affected (0.00 sec)

...

mysql> insert into foo SET the_key = Null;
Query OK, 1 row affected (0.00 sec)

mysql> select * from foo;
+------------+
| the_key    |
+------------+
| 0000000001 |
| 0000000002 |
| 0000000003 |
| 0000000004 |
| 0000000005 |
| 0000000006 |
| 0000000007 |
| 0000000008 |
+------------+
8 rows in set (0.00 sec)

You may need to look into using a smallint (5 digits), or trimming/padding.

您可能需要考虑使用 smallint(5 位数字)或修剪/填充。

回答by jonstjohn

If you need the auto_increment column in a zero padded format, I suggest that you display it as such and not attempt to store it in the database that way.

如果您需要零填充格式的 auto_increment 列,我建议您按原样显示它,而不是尝试以这种方式将其存储在数据库中。

In PHP, you could use the following code to display or otherwise use the id:

在 PHP 中,您可以使用以下代码来显示或以其他方式使用 id:

$padded_id = str_pad($id, 4, '0');

回答by Hawk Kroeger

To pad in the database set the id column to ZEROFILL

要填充数据库,请将 id 列设置为 ZEROFILL

But if its for display purposes only I recommend using LPADSELECT RIGHT('000000' + yourNum, 6);

但如果仅用于显示目的,我建议使用LPADSELECT RIGHT('000000' + yourNum, 6);

回答by Steven A. Lowe

is the field an integer? if so, the answer is, "why? it's an integer!" ;-)

该字段是整数吗?如果是这样,答案是,“为什么?它是一个整数!” ;-)