ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

mysql-自动增量重置为0,但是不能插入id = 0的值.值> 0不会发生

2019-10-30 12:14:05  阅读:274  来源: 互联网

标签:sql-insert mariadb auto-increment mysql


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

想象一下,我们有一个餐桌顾客:

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”和插入值? (是的,我以后可以编辑,但由于各种原因,对于我的情况而言,这是不切实际的).

谢谢!

解决方法:

我已经参考了link的答案

您可以使用:

SET [GLOBAL|SESSION] sql_mode='NO_AUTO_VALUE_ON_ZERO'

如此处所述,这将防止MySQL将INSERT / UPDATE ID 0解释为下一个序列ID.这种行为将被限制为NULL.

这就是我认为应用程序中非常糟糕的行为.您必须非常谨慎地确保它的使用一致,尤其是如果您选择以后实施复制时.

标签:sql-insert,mariadb,auto-increment,mysql
来源: https://codeday.me/bug/20191030/1967692.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有