在MySQL中,当存在“重复条目”时,错误,如何防止主键自动递增? [英] In MySQL, when there is a "duplicate entry" error, how do I prevent the primary key from auto incrementing?
本文介绍了在MySQL中,当存在“重复条目”时,错误,如何防止主键自动递增?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不希望主键增加,即使它命中重复的输入错误!
I don't want the primary key to increment, even if it hits the duplicate entry error!!
推荐答案
可以使用表和触发器来实现类似oracle的序列:
You could use a table and triggers to implement an oracle like sequence:
drop table if exists users_seq;
create table users_seq
(
next_val int unsigned not null default 0
)
engine=innodb;
drop table if exists users;
create table users
(
user_id int unsigned not null,
username varchar(32) unique not null
)
engine=innodb;
delimiter #
create trigger users_before_ins_trig before insert on users
for each row
begin
declare v_id int unsigned default 0;
select next_val + 1 into v_id from users_seq;
set new.user_id = v_id;
update users_seq set next_val = v_id;
end#
delimiter ;
insert into users_seq values (0);
insert into users (username) values ('alpha'),('beta');
Query OK, 2 rows affected, 1 warning (0.03 sec)
select * from users_seq;
+----------+
| next_val |
+----------+
| 2 |
+----------+
1 row in set (0.00 sec)
select * from users;
+---------+----------+
| user_id | username |
+---------+----------+
| 1 | alpha |
| 2 | beta |
+---------+----------+
2 rows in set (0.00 sec)
insert into users (username) values ('alpha');
ERROR 1062 (23000): Duplicate entry 'alpha' for key 'username'
select * from users_seq;
+----------+
| next_val |
+----------+
| 2 |
+----------+
1 row in set (0.00 sec)
select * from users;
+---------+----------+
| user_id | username |
+---------+----------+
| 1 | alpha |
| 2 | beta |
+---------+----------+
2 rows in set (0.00 sec)
insert into users (username) values ('gamma');
Query OK, 1 row affected, 1 warning (0.03 sec)
select * from users_seq;
+----------+
| next_val |
+----------+
| 3 |
+----------+
1 row in set (0.00 sec)
select * from users;
+---------+----------+
| user_id | username |
+---------+----------+
| 1 | alpha |
| 2 | beta |
| 3 | gamma |
+---------+----------+
3 rows in set (0.00 sec)
希望它有帮助:)
这篇关于在MySQL中,当存在“重复条目”时,错误,如何防止主键自动递增?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文