自动增量重置为0,但无法插入id=0的值。对于值 >0

问题描述 投票:0回答:3

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

想象我们有一桌顾客:

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”? (是的,我可以事后编辑,但由于各种原因,这对我的情况来说不切实际)。

谢谢!

mysql auto-increment sql-insert mariadb
3个回答
10
投票

我已经从链接

引用了答案

您可以使用:

SET [GLOBAL|SESSION] sql_mode='NO_AUTO_VALUE_ON_ZERO'

如此处所述,将阻止 MySQL 将 INSERT/UPDATE ID 0 解释为下一个序列 ID。此类行为将被限制为 NULL。

我认为应用程序的行为非常糟糕。您必须非常小心,确保其使用一致,特别是如果您选择稍后实施复制。


0
投票

INSERT INTO 之后,获取最后一条记录并使用 UPDATE id = 0;


-1
投票

这是不可能的。

0 保留给 auto_increment 字段。当您插入自动增量行 0 或 null 时,mysql 会插入具有当前自动增量值的记录。

© www.soinside.com 2019 - 2024. All rights reserved.