How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?
Here you go:
USE information_schema;SELECT *FROM KEY_COLUMN_USAGEWHERE REFERENCED_TABLE_NAME = 'X' AND REFERENCED_COLUMN_NAME = 'X_id';
If you have multiple databases with similar tables/column names you may also wish to limit your query to a particular database:
SELECT *FROM KEY_COLUMN_USAGEWHERE REFERENCED_TABLE_NAME = 'X' AND REFERENCED_COLUMN_NAME = 'X_id' AND TABLE_SCHEMA = 'your_database_name';
MySQL 5.5 Reference Manual: "InnoDB and FOREIGN KEY Constraints"
SELECT ke.REFERENCED_TABLE_SCHEMA parentSchema, ke.referenced_table_name parentTable, ke.REFERENCED_COLUMN_NAME parentColumnName, ke.TABLE_SCHEMA ChildSchema, ke.table_name childTable, ke.COLUMN_NAME ChildColumnNameFROM information_schema.KEY_COLUMN_USAGE keWHERE ke.referenced_table_name IS NOT NULL AND ke.REFERENCED_COLUMN_NAME = 'ci_id' ## Find Foreign Keys linked to this Primary KeyORDER BY ke.referenced_table_name;
This solution will not only display all relations but also the constraint name, which is required in some cases (e.g. drop constraint):
SELECT CONCAT(table_name, '.', column_name) AS 'foreign key', CONCAT(referenced_table_name, '.', referenced_column_name) AS 'references', constraint_name AS 'constraint name'FROM information_schema.key_column_usageWHERE referenced_table_name IS NOT NULL;
If you want to check tables in a specific database, add the following:
AND table_schema = 'database_name';