How do I see all foreign keys to a table or column?

后端 未结 13 1062
忘了有多久
忘了有多久 2020-11-22 09:14

In MySQL, how do I get a list of all foreign key constraints pointing to a particular table? a particular column? This is the same thing as this Oracle question, but for MyS

13条回答
  •  星月不相逢
    2020-11-22 09:43

    I'm reluctant to add yet another answer, but I've had to beg, borrow and steal from the others to get what I want, which is a complete list of all the FK relationships on tables in a given schema, INCLUDING FKs to tables in other schemas. The two crucial recordsets are information_schema.KEY_COLUMN_USAGE and information_schema.referential_constraints. If an attribute you want is missing, just uncomment the KCU., RC. to see what's available

    SELECT DISTINCT KCU.TABLE_NAME, KCU.COLUMN_NAME, REFERENCED_TABLE_SCHEMA, KCU.REFERENCED_TABLE_NAME, KCU.REFERENCED_COLUMN_NAME, UPDATE_RULE, DELETE_RULE #, KCU.*, RC.*
    FROM information_schema.KEY_COLUMN_USAGE KCU
    INNER JOIN information_schema.referential_constraints RC ON KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
    WHERE TABLE_SCHEMA = (your schema name)
    AND KCU.REFERENCED_TABLE_NAME IS NOT NULL
    ORDER BY KCU.TABLE_NAME, KCU.COLUMN_NAME;
    

提交回复
热议问题