MySQL: How to determine foreign key relationships programmatically?

白昼怎懂夜的黑 提交于 2019-11-27 18:37:07

There are two tables you can query to get this information: INFORMATION_SCHEMA.TABLE_CONSTRAINTS and INFORMATION_SCHEMA.KEY_COLUMN_USAGE.

Here's a query from the comments on the latter page linked above, which demonstrates how to get the info you seek.

SELECT CONCAT( table_name, '.', column_name, ' -> ', 
  referenced_table_name, '.', referenced_column_name ) AS list_of_fks 
FROM INFORMATION_SCHEMA.key_column_usage 
WHERE referenced_table_schema = 'test' 
  AND referenced_table_name IS NOT NULL 
ORDER BY table_name, column_name;

Use your schema name instead of 'test' above.

JavierCane

Here you have a little improvement over the @bill solution:

SELECT CONSTRAINT_SCHEMA AS db,
       CONCAT (
           TABLE_NAME,
           '.',
           COLUMN_NAME,
           ' -> ',
           REFERENCED_TABLE_NAME,
           '.',
           REFERENCED_COLUMN_NAME
       ) AS relationship 
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME = 'your_table_name'
ORDER BY CONSTRAINT_SCHEMA,
         TABLE_NAME,
         COLUMN_NAME;

In this case I was filtering by relationships with the "your_table_name" fields and seeing from which database the relationship comes.

Try INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS

Bkeshh Mhrjn
SELECT TABLE_NAME,
       COLUMN_NAME,
       CONSTRAINT_NAME,
       REFERENCED_TABLE_NAME,
       REFERENCED_COLUMN_NAME 
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME = 'table_name'
      AND TABLE_SCHEMA = 'table_schema';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!