如何将键0插入mysql的AUTO_INCREMENT行?

时间:2012-10-07 02:35:34

标签: mysql

  

可能重复:
  How to force MySQL to take 0 as a valid auto-increment value

我知道我可以对现有行进行更新,但是可以插入ID为0的行吗?

mysql> create table inc( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, sz TEXT);
Query OK, 0 rows affected (0.10 sec)

mysql> insert into inc(id, sz) select 25, "a";
Query OK, 1 row affected (0.02 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> insert into inc(id, sz) select 25, "a";
ERROR 1062 (23000): Duplicate entry '25' for key 'PRIMARY'
mysql> insert into inc(id, sz) select 27, "b";
Query OK, 1 row affected (0.04 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> insert into inc(id, sz) select -5, "c";
Query OK, 1 row affected (0.03 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> insert into inc(id, sz) select 0, "d";
Query OK, 1 row affected (0.15 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select * from inc;
+----+------+
| id | sz   |
+----+------+
| -5 | c    |
| 25 | a    |
| 27 | b    |
| 28 | d    |
+----+------+
4 rows in set (0.00 sec)

1 个答案:

答案 0 :(得分:1)

来自http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

“没有为AUTO_INCREMENT列指定任何值,因此MySQL会自动分配序列号。您还可以显式为列分配NULL或0以生成序列号。”

所以似乎使用0只是告诉它auto_increment。

但是如果要分配ID号,我不确定为什么要定义列以使用AUTO_INCREMENT?