views:

875

answers:

4

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 MySQL.

+1  A: 

If you use InnoDB and defined FK's you could query the information_schema database e.g.:

SELECT * FROM information_schema.TABLE_CONSTRAINTS 
WHERE information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY' 
AND information_schema.TABLE_CONSTRAINTS.TABLE_SCHEMA = 'myschema'
AND information_schema.TABLE_CONSTRAINTS.TABLE_NAME = 'mytable';
Node
actually, that points the wrong direction. that query shows all the foreign keys pointing FROM 'mytable', not all foreign keys pointing TO 'mytable'.
Christian Oudard
I think Vinko Vrsalovic posted a good solution. *upvote* =)
Node
A: 

Take a look at INFORMATION_SCHEMA.TABLE_CONSTRAINTS, as described here.

JosephStyons
A: 

The solution I came up with is fragile; it relies on django's naming convention for foreign keys.

USE information_schema;
tee mysql_output
SELECT * FROM TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_SCHEMA = 'database_name';
notee

Then, in the shell,

grep 'refs_tablename_id' mysql_output
Christian Oudard
+2  A: 

For a table

use INFORMATION_SCHEMA;

select TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME from KEY_COLUMN_USAGE where
REFERENCED_TABLE_NAME = '<table>';

for a column, the same but add an and for the REFERENCED_COLUMN_NAME.

Vinko Vrsalovic