52

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?

  • 3
    http://stackoverflow.com/q/806989 has more votes than this question... Though this was asked and answered before that. – Fr0zenFyr Sep 16 '15 at 08:57

8 Answers8

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

This works.

informatik01
  • 16,038
  • 10
  • 74
  • 104
12
select table_name 
from information_schema.referential_constraints 
where referenced_table_name = 'parent table here';
Michael Buen
  • 38,643
  • 9
  • 94
  • 118
  • The table referential_constraints does not exist in information_schema. I was looking in this database for an answer but can't find it. MySQL version is 5.0.51a-24-log (Debian) –  Apr 16 '09 at 02:47
2

If you have phpMyAdmin installed, you can use its designer feature to visualize table relationships.

enter image description here

To use the designer, select a database, then look for the Designer tab.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
0

you could try MySql workbench which allows you to extract E.R. diagram. In this you can find all you need about tables of your database.

user7209199
  • 59
  • 1
  • 10
-1

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

Rajon Tanducar
  • 308
  • 4
  • 8
-1

Use Toad to load it up and you can view the references through the diagram. also make sure that you don't have any app code passing sql from the front-end, dropping the table may cause the app to break.

Download link http://www.toadsoft.com/toadmysql/FreewareDownload.htm

If you are using innoDB try this one SHOW TABLE STATUS FROM yourdatabasename LIKE 'T' http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html

Srikar Doddi
  • 15,499
  • 15
  • 65
  • 106
  • If you are using innoDB try this one SHOW TABLE STATUS FROM yourdatabasename LIKE 'T' http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html – Srikar Doddi Apr 16 '09 at 02:55
-1

Look at the KEY_COLUMN_USAGE table in the iformation_schema schema.

Milhous
  • 14,473
  • 16
  • 63
  • 82
-1

from the mysql command line: show table status

Will Glass
  • 4,800
  • 6
  • 34
  • 44