Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

No MySQL, quando há um erro de entrada duplicada, como evito que a chave primária seja incrementada automaticamente?


Você pode usar uma tabela e gatilhos para implementar uma sequência do tipo oráculo:
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)

espero que ajude :)