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

后端 未结 13 1047
忘了有多久
忘了有多久 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 09:40

    This solution will not only display all relations but also the constraint name, which is required in some cases (e.g. drop contraint):

    select
        concat(table_name, '.', column_name) as 'foreign key',
        concat(referenced_table_name, '.', referenced_column_name) as 'references',
        constraint_name as 'constraint name'
    from
        information_schema.key_column_usage
    where
        referenced_table_name is not null;
    

    If you want to check tables in a specific database, at the end of the query add the schema name:

    select
        concat(table_name, '.', column_name) as 'foreign key',
        concat(referenced_table_name, '.', referenced_column_name) as 'references',
        constraint_name as 'constraint name'
    from
        information_schema.key_column_usage
    where
        referenced_table_name is not null
        and table_schema = 'database_name';
    

    Likewise, for a specific column name, add

    and table_name = 'table_name

    at the end of the query.

    Inspired by this post here

提交回复
热议问题