Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Ngăn chặn insert trùng lặp (duplicate entry) trong MySQL dùng UNIQUE constraint

Thêm ràng buộc UNIQUE trên một hoặc nhiều cột để database tự chặn việc insert dữ liệu trùng lặp.

Ví dụ

Tạo bảng:

mysql> create table DemoTable ( 
    Id int, 
    Name varchar(100) 
); 
Query OK, 0 rows affected (0.79 sec)

Thêm UNIQUE constraint trên cặp (Id, Name):

mysql> alter table DemoTable add constraint id_NameUnKey UNIQUE(Id,Name); 
Query OK, 0 rows affected (0.82 sec) 
Records: 0  Duplicates: 0  Warnings: 0

Thử insert trùng:

mysql> insert into DemoTable values(11,'John'); 
Query OK, 1 row affected (0.18 sec) 
mysql> insert into DemoTable values(12,'John'); 
Query OK, 1 row affected (0.21 sec) 
mysql> insert into DemoTable values(11,'John'); 
ERROR 1062 (23000): Duplicate entry '11-John' for key 'id_NameUnKey'

Dữ liệu chỉ còn 2 hàng unique:

+------+------+
| Id   | Name |
+------+------+
| 11   | John |
| 12   | John |
+------+------+

Các dạng UNIQUE:

  • UNIQUE(cot) - cột đơn lẻ không trùng
  • UNIQUE(cot1, cot2) - cặp kết hợp không trùng (composite unique)
  • Tạo khi CREATE TABLE: CREATE TABLE ... UNIQUE KEY tenKey (cot1, cot2)

Xử lý trùng lặp mềm: Dùng INSERT IGNORE, INSERT ... ON DUPLICATE KEY UPDATE, hoặc REPLACE INTO.