如何解决在Mysql中使用重复值停止自动递增
我有一个称为注释的表,其中有一个具有唯一键的文本列和一个具有自动递增的优先键id列,如果插入重复的文本会产生错误,但也会增加我的id列。有没有一种方法可以在出现重复值时停止自动递增,并且仅在插入记录时才递增?我已经尝试了innodb_autoinc_lock_mode = 0,但仍然无法正常工作,并且还尝试了插入忽略,但计数器仍然上升。我正在使用Mysql 5.7。 谢谢
解决方法
您可以在/etc/my.cnf中设置 innodb_autoinc_lock_mode 。在这种情况下,它适合您。另请参见https://mariadb.com/kb/en/auto_increment-handling-in-innodb/
将此行添加到mysqld部分的配置中,然后重新启动mysql服务
[mysqld]
innodb_autoinc_lock_mode = 0
查看已设置的模式
MariaDB [(none)]> show variables like 'innodb_autoinc_lock_mode';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| innodb_autoinc_lock_mode | 0 |
+--------------------------+-------+
1 row in set (0.00 sec)
样品
MariaDB [bernd]> CREATE TABLE IF NOT EXISTS `docs` (
-> `id` int(6) unsigned NOT NULL AUTO_INCREMENT,-> `rev` int(3) unsigned NOT NULL,-> `content` varchar(200) NOT NULL,-> PRIMARY KEY (`id`,`rev`),-> unique KEY (content)
-> ) DEFAULT CHARSET=utf8;
/*INSERT INTO `docs` Query OK,0 rows affected (0.01 sec)
MariaDB [bernd]> /*INSERT INTO `docs` ( `rev`,`content`) VALUES
/*> ( '1','The earth is flat'),/*> ( '1','One hundred angels can dance on the head of a pin'),/*> ( '2','The earth is flat and rests on a bull\'s horn'),/*> ( '3','The earth is like a ball.');*/
MariaDB [bernd]>
MariaDB [bernd]> INSERT IGNORE INTO `docs` ( `rev`,`content`) VALUES
-> ('1',-> ('1',-> ('2',-> ('3','X The earth is like a ball.');
INSQuery OK,4 rows affected,1 warning (0.01 sec)
Records: 5 Duplicates: 1 Warnings: 1
MariaDB [bernd]> INSERT IGNORE INTO `docs` ( `rev`,`content`) VALUES
-> ('5','The earth is flat type');
Query OK,1 row affected (0.00 sec)
MariaDB [bernd]> SELECT * from DOCS ORDER by id;
ERROR 1146 (42S02): Table 'bernd.DOCS' doesn't exist
MariaDB [bernd]> SELECT * from docs ORDER by id;
+----+-----+---------------------------------------------------+
| id | rev | content |
+----+-----+---------------------------------------------------+
| 1 | 1 | The earth is flat |
| 2 | 1 | One hundred angels can dance on the head of a pin |
| 3 | 2 | The earth is flat and rests on a bull's horn |
| 4 | 3 | X The earth is like a ball. |
| 5 | 5 | The earth is flat type |
+----+-----+---------------------------------------------------+
5 rows in set (0.00 sec)
MariaDB [bernd]>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。