คำสั่งดู Foreign Key เท่านั้น
ใช้ตาราง information_schema.referential_constraints ซึ่งเก็บเฉพาะ Foreign Key Constraints:
SELECT * FROM information_schema.referential_constraints
WHERE constraint_schema = 'your_database_name';
ตัวอย่างจากฐานข้อมูล "business"
SELECT * FROM information_schema.referential_constraints
WHERE constraint_schema = 'business';
คอลัมน์สำคัญ
| คอลัมน์ | ความหมาย |
|---|---|
| CONSTRAINT_NAME | ชื่อ Foreign Key Constraint |
| TABLE_NAME | ตารางลูก (Child Table) ที่มี FK |
| REFERENCED_TABLE_NAME | ตารางแม่ (Parent Table) ที่ถูกอ้างอิง |
| UNIQUE_CONSTRAINT_NAME | ชื่อ Constraint ที่ถูกอ้างอิง (มักเป็น PRIMARY) |
| UPDATE_RULE | กติกาเมื่อ Update ตารางแม่ (CASCADE, SET NULL, NO ACTION, RESTRICT) |
| DELETE_RULE | กติกาเมื่อ Delete ตารางแม่ (CASCADE, SET NULL, NO ACTION, RESTRICT) |
ตัวอย่างผลลัพธ์
+--------------------+-------------------+--------------------------+---------------------------+--------------------------+------------------------+--------------+-------------+-------------+-------------------+-----------------------+
| CONSTRAINT_CATALOG | CONSTRAINT_SCHEMA | CONSTRAINT_NAME | UNIQUE_CONSTRAINT_CATALOG | UNIQUE_CONSTRAINT_SCHEMA | UNIQUE_CONSTRAINT_NAME | MATCH_OPTION | UPDATE_RULE | DELETE_RULE | TABLE_NAME | REFERENCED_TABLE_NAME |
+--------------------+-------------------+--------------------------+---------------------------+--------------------------+------------------------+--------------+-------------+-------------+-------------------+-----------------------+
| def | business | ConstChild | def | business | PRIMARY | NONE | NO ACTION | NO ACTION | childdemo | parentdemo |
| def | business | ConstFK | def | business | PRIMARY | NONE | NO ACTION | NO ACTION | tblf | tblp |
| def | business | constFKPK | def | business | PRIMARY | NONE | NO ACTION | NO ACTION | foreigntable | primarytable1 |
| def | business | FKConst | def | business | PRIMARY | NONE | NO ACTION | NO ACTION | foreigntabledemo | primarytabledemo |
| def | business | primarytable1demo_ibfk_1 | def | business | PRIMARY | NONE | NO ACTION | NO ACTION | primarytable1demo | foreigntable1 |
| def | business | StudCollegeConst | def | business | PRIMARY | NONE | NO ACTION | NO ACTION | studentenrollment | college |
+--------------------+-------------------+--------------------------+---------------------------+--------------------------+------------------------+--------------+-------------+-------------+-------------------+-----------------------+
ดูรายละเอียดคอลัมน์ FK (Join กับ key_column_usage)
SELECT
rc.CONSTRAINT_NAME,
rc.TABLE_NAME AS child_table,
kcu.COLUMN_NAME AS child_column,
rc.REFERENCED_TABLE_NAME AS parent_table,
kcu.REFERENCED_COLUMN_NAME AS parent_column,
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';