Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Wie verhindere ich in MySQL, dass der Primärschlüssel automatisch erhöht wird, wenn ein doppelter Eintragsfehler auftritt?

Sie könnten eine Tabelle und Trigger verwenden, um eine Orakel-ähnliche Sequenz zu implementieren:

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)

hoffe es hilft :)