Sử dụng bảng information_schema.table_constraints để liệt kê mọi ràng buộc: PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK.
Cú pháp
SELECT * FROM information_schema.table_constraints WHERE constraint_schema = 'your_database_name';
Ví dụ với database "business"
mysql> SELECT * FROM information_schema.table_constraints WHERE constraint_schema = 'business';
Kết quả mẫu (rút gọn):
| CONSTRAINT_NAME | TABLE_NAME | CONSTRAINT_TYPE |
|---|---|---|
| PRIMARY | primarytable | PRIMARY KEY |
| UserId | usernameandpassworddemo | UNIQUE |
| ConstFK | tabledemo2 | UNIQUE |
| constFKPK | foreigntable | FOREIGN KEY |
| FKConst | foreigntabledemo | FOREIGN KEY |
| StudCollegeConst | studentenrollment | FOREIGN KEY |
Các loại CONSTRAINT_TYPE phổ biến
- PRIMARY KEY: Khóa chính
- FOREIGN KEY: Khóa ngoại
- UNIQUE: Ràng buộc duy nhất
- CHECK: Ràng buộc kiểm tra (MySQL 8.0.16+)
Truy vấn hữu ích khác
Chỉ lấy FOREIGN KEY:
SELECT * FROM information_schema.table_constraints WHERE constraint_schema = 'business' AND constraint_type = 'FOREIGN KEY';
Đếm số lượng từng loại:
SELECT constraint_type, COUNT(*) FROM information_schema.table_constraints WHERE constraint_schema = 'business' GROUP BY constraint_type;