Mysql 自动递增重置为0,但无法插入id为0的值。不适用于值>;0

Mysql 自动递增重置为0,但无法插入id为0的值。不适用于值>;0,mysql,auto-increment,sql-insert,mariadb,Mysql,Auto Increment,Sql Insert,Mariadb,我刚刚偶然发现了一个非常奇怪的行为: 假设我们有一张桌子,顾客: MariaDB [connections]> describe customers; +--------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+-------------

我刚刚偶然发现了一个非常奇怪的行为:

假设我们有一张桌子,顾客:

MariaDB [connections]> describe customers;
+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| customerId   | int(11)     | NO   | PRI | NULL    | auto_increment |
| customerName | varchar(50) | NO   |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
插入两个值:

insert into customers(customerName) values('Foo');
insert into customers(customerName) values('Bar');
然后删除所有内容并重置自动增量:

DELETE FROM customers;
ALTER TABLE customers AUTO_INCREMENT = 0;
现在,插入customerId=0的新值:

INSERT INTO customers(customerId,customerName) VALUES(0,'Site owner');
并看到结果:

MariaDB [connections]> select * from customers;
+------------+--------------+
| customerId | customerName |
+------------+--------------+
|          1 | Site owner   |
+------------+--------------+
1 row in set (0.00 sec)
customerId设置为1

重复相同的步骤,但重置为5并插入5,一切正常:

MariaDB [connections]> delete from customers;
Query OK, 1 row affected (0.00 sec)

MariaDB [connections]> ALTER TABLE customers AUTO_INCREMENT = 5;
Query OK, 0 rows affected (0.00 sec)               
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [connections]> INSERT INTO customers(customerId,customerName) VALUES(5,'Site owner');
Query OK, 1 row affected (0.00 sec)

MariaDB [connections]> select * from customers;
+------------+--------------+
| customerId | customerName |
+------------+--------------+
|          5 | Site owner   |
+------------+--------------+
1 row in set (0.00 sec)
这是怎么回事?如何使用插入值插入值“0”?(是的,我可以在事后进行编辑,但由于各种原因,这对我的情况并不实际)

谢谢

这是不可能的


0为自动增量字段保留。当您插入到自动递增行0或null时,请使用当前的自动递增值插入记录。

我已经从

您可以使用:

SET [GLOBAL|SESSION] sql_mode='NO_AUTO_VALUE_ON_ZERO'
这将阻止MySQL将插入/更新ID 0解释为下一个序列ID。这种行为将被限制为NULL


这是我从应用程序中考虑到的不良行为。您必须非常小心它的一致性,尤其是如果您选择在以后实施复制的话。

我可以立即告诉您一件事,您可以相信我,或者干脆放弃它,忘掉它,记住我告诉您的,当它咬到您的屁股时(它会的)。永远不要依靠自动增量来提供对您有意义的数字。没有自动递增,所以我们可以使用它进行顺序编号。它只有一个目的——唯一地标识一行。这意味着mysql可以丢弃一些数字(当插入失败时),它可以抵消这些数字,它可以使用负值等。如果你需要一些“特殊”数字,就让它去吧——添加另一列或类似的内容。这可以从命令行开始工作,但不使用mysqli的$link->query()。我错过了什么吗?这救了我今天。非常感谢。