MySQL: How do I find out which tables reference a specific table?

Viewed 34639

I want to drop a table but it is referenced by one or more other tables. How can I find out which tables are referencing this table without having to look at each of the tables in the database one by one?

8 Answers
SELECT TABLE_NAME
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = 'your_schema_name'
      AND REFERENCED_TABLE_NAME = 'your_table_name';

This works.

select table_name 
from information_schema.referential_constraints 
where referenced_table_name = 'parent table here';

Look at the KEY_COLUMN_USAGE table in the iformation_schema schema.

from the mysql command line: show table status

If you also want the specific column where the references are made use the following query.

SELECT 
ku.CONSTRAINT_NAME AS "Foreign key",
CONCAT("`", ku.TABLE_SCHEMA, "`.`", ku.TABLE_NAME, "`") AS "In",
GROUP_CONCAT(ku.COLUMN_NAME) AS "Source column",
CONCAT("`", ku.REFERENCED_TABLE_SCHEMA, "`.`", ku.REFERENCED_TABLE_NAME, "`") AS 
"References",
GROUP_CONCAT(ku.REFERENCED_COLUMN_NAME) AS "Target column"
FROM information_schema.KEY_COLUMN_USAGE AS ku
WHERE ku.REFERENCED_TABLE_SCHEMA = '[THE_CURRENT_SELECTED_SCHEMA_NAME]'
AND ku.REFERENCED_TABLE_NAME = '[THE_CURRENT_SELECTED_TABLE_NAME]'
GROUP BY ku.CONSTRAINT_NAME
HAVING `In` != `References`

enter image description here

Related