Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Di MySQL, ketika ada kesalahan entri duplikat, bagaimana cara mencegah kunci utama bertambah secara otomatis?

Anda dapat menggunakan tabel dan pemicu untuk mengimplementasikan urutan seperti oracle:

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)

semoga membantu :)



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. MySQL SELECT SUM berdasarkan tabel lain

  2. SailsJS dan nama ID kustom mySQL tidak berfungsi dengan cetakan biru

  3. kategori mysql dan daftar subkategori

  4. MySQL Rata-rata Setiap 4 Baris

  5. MySQL Workbench:Tidak dapat terhubung ke server MySQL pada kesalahan 127.0.0.1' (10061)