Computer >> Máy Tính >  >> Lập trình >> MySQL

Chúng ta có thể thực thi tính duy nhất phức hợp trong MySQL không?

Có, chúng tôi có thể làm được điều đó. Để hiểu rõ, trước tiên chúng ta hãy tạo một bảng -

mysql> create table enforceCompoundUniqueness
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(40) NOT NULL,
   -> StudentMobileNumber varchar(12) NOT NULL,
   -> UNIQUE StudentName_StudentMobileNumber(StudentName,StudentMobileNumber)
   -> );
Query OK, 0 rows affected (0.60 sec)

Sau đây là truy vấn để chèn các bản ghi trong bảng bằng cách sử dụng lệnh insert -

mysql> insert into enforceCompoundUniqueness(StudentName,StudentMobileNumber)
values('Larry','2322245676');
Query OK, 1 row affected (0.18 sec)

mysql> insert into enforceCompoundUniqueness(StudentName,StudentMobileNumber)
values('Larry','2322245676');
ERROR 1062 (23000): Duplicate entry 'Larry-2322245676' for key
'StudentName_StudentMobileNumber'

mysql> insert into enforceCompoundUniqueness(StudentName,StudentMobileNumber)
values('Sam','6475746455');
Query OK, 1 row affected (0.13 sec)

Trong truy vấn trên, nếu bạn cố gắng chèn các bản ghi trùng lặp, bạn có thể thấy lỗi vì chúng tôi đã thực thi tính duy nhất.

Sau đây là truy vấn để hiển thị tất cả các bản ghi từ bảng bằng cách sử dụng câu lệnh select -

mysql> select * from enforceCompoundUniqueness;

Điều này sẽ tạo ra kết quả sau -

+-----------+-------------+---------------------+
| StudentId | StudentName | StudentMobileNumber |
+-----------+-------------+---------------------+
| 1         | Larry       | 2322245676          |
| 3         | Sam         | 6475746455          |
+-----------+-------------+---------------------+
2 rows in set (0.00 sec)