Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: How to determine foreign key relationships programmatically?

Similar to this question but for MySQL....

How can I programmatically determine foreign key references in MySQL (assuming InnoDB)? I can almost get them with:

SHOW TABLE STATUS WHERE Name = 'MyTableName';

...but alas, the comment column which seems to contain some of this info gets truncated so I can't rely on it. There must be some other way...

I'd be happy with a C API call, a SQL statement, anything--I just need something that consistently works.

Note: I've also considered parsing the results of a "SHOW CREATE TABLE MyTableName" statement, but I'm really hoping there's something simpler.

like image 517
Drew Hall Avatar asked Nov 07 '08 22:11

Drew Hall


3 Answers

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.

like image 103
Bill Karwin Avatar answered Nov 08 '22 02:11

Bill Karwin


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.

like image 21
JavierCane Avatar answered Nov 08 '22 03:11

JavierCane


Try INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS

like image 2
Cade Roux Avatar answered Nov 08 '22 02:11

Cade Roux