Truy vấn bảng information_schema.referential_constraints để liệt kê chỉ các FOREIGN KEY constraints.
Cú pháp
SELECT * FROM information_schema.referential_constraints WHERE constraint_schema = 'your_database_name';
Ví dụ với database "business"
mysql> SELECT * FROM information_schema.referential_constraints WHERE constraint_schema = 'business';
Kết quả mẫu (các cột quan trọng):
| CONSTRAINT_NAME | TABLE_NAME | REFERENCED_TABLE_NAME | UPDATE_RULE | DELETE_RULE |
|---|---|---|---|---|
| ConstChild | childdemo | parentdemo | NO ACTION | NO ACTION |
| ConstFK | tblf | tblp | NO ACTION | NO ACTION |
| constFKPK | foreigntable | primarytable1 | NO ACTION | NO ACTION |
| FKConst | foreigntabledemo | primarytabledemo | NO ACTION | NO ACTION |
| StudCollegeConst | studentenrollment | college | NO ACTION | NO ACTION |
Giải thích các cột
- CONSTRAINT_NAME: Tên khóa ngoại
- TABLE_NAME: Bảng con (chứa khóa ngoại)
- REFERENCED_TABLE_NAME: Bảng cha (bị tham chiếu)
- UPDATE_RULE / DELETE_RULE: Hành động khi UPDATE/DELETE bản ghi cha:
CASCADE,SET NULL,NO ACTION,RESTRICT,SET DEFAULT. - MATCH_OPTION: Thường là
NONE(MySQL không hỗ trợ MATCH FULL/PARTIAL).
Truy vấn chi tiết hơn (kèm cột FK)
SELECT rc.constraint_name, rc.table_name, kcu.column_name, rc.referenced_table_name, kcu.referenced_column_name, rc.update_rule, rc.delete_rule FROM information_schema.referential_constraints rc JOIN information_schema.key_column_usage kcu ON rc.constraint_name = kcu.constraint_name AND rc.constraint_schema = kcu.constraint_schema WHERE rc.constraint_schema = 'business';