Code Fragment: How to programatically get MySQL table relationships

This magical chunk of goodness will allow you to query a mysql database to determine what table fields are foreign keys, and what they reference. Just replace ‘database_name’ and ‘table_name’ with the respective names you want:

1
2
3
4
5
6
7
SELECT column_name, referenced_table_name,
referenced_column_name
FROM information_schema.key_column_usage
WHERE table_schema='database_name'
AND table_name='table_name'
AND referenced_table_name IS NOT NULL
AND referenced_column_name IS NOT NULL;

0 comments ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment