How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?
Solution 1:
Here you go:
USE information_schema;
SELECT *
FROM
KEY_COLUMN_USAGE
WHERE
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_USAGE
WHERE
REFERENCED_TABLE_NAME = 'X'
AND REFERENCED_COLUMN_NAME = 'X_id'
AND TABLE_SCHEMA = 'your_database_name';
Solution 2:
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 ChildColumnName
FROM
information_schema.KEY_COLUMN_USAGE ke
WHERE
ke.referenced_table_name IS NOT NULL
AND ke.REFERENCED_COLUMN_NAME = 'ci_id' ## Find Foreign Keys linked to this Primary Key
ORDER BY
ke.referenced_table_name;
Solution 3:
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_usage
WHERE
referenced_table_name IS NOT NULL;
If you want to check tables in a specific database, add the following:
AND table_schema = 'database_name';
Solution 4:
You can find all schema related information in the wisely named information_schema
table.
You might want to check the table REFERENTIAL_CONSTRAINTS
and KEY_COLUMN_USAGE
. The former tells you which tables are referenced by others; the latter will tell you how their fields are related.
Solution 5:
Listing all foreign keys in a db including description
SELECT
i1.CONSTRAINT_NAME, i1.TABLE_NAME,i1.COLUMN_NAME,
i1.REFERENCED_TABLE_SCHEMA,i1.REFERENCED_TABLE_NAME, i1.REFERENCED_COLUMN_NAME,
i2.UPDATE_RULE, i2.DELETE_RULE
FROM
information_schema.KEY_COLUMN_USAGE AS i1
INNER JOIN
information_schema.REFERENTIAL_CONSTRAINTS AS i2
ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.REFERENCED_TABLE_NAME IS NOT NULL
AND i1.TABLE_SCHEMA ='db_name';
restricting to a specific column in a table table
AND i1.table_name = 'target_tb_name' AND i1.column_name = 'target_col_name'