Below is the example relationship among tables.
A <- B <- C <- D
// B is using one column of A as the foreign key column.
// C is using one column of B as the foreign key column.
...
I want to get all the nested referencing relationship among tables, not just one depth relationship such as A <- B
I tried to solve this problem with information_schema
USE information_schema;
SELECT *
FROM
KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_NAME = 'user3'
AND REFERENCED_COLUMN_NAME = 'id';
I searched this partial answer in stackoverflow, but it is hard for me to make this query recursive one(or, nested, iterative) to get all the connection in the entire DB.
If you can give a tip to solve my problem with information_schema
, or other approaches, I would appreciate your help.
If you are using MySQL 8+, a recursive CTE might get the job done here. The recursive join condition would be that the current table refers to the parent of the previous step in the recursion.
WITH RECURSIVE cte AS (
SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = 'yourSchema' AND TABLE_NAME = 'user3' AND COLUMN_NAME = 'id'
UNION ALL
SELECT k1.TABLE_SCHEMA, k1.TABLE_NAME, k1.COLUMN_NAME
FROM KEY_COLUMN_USAGE k1
INNER JOIN cte k2
ON k1.TABLE_NAME = k2.REFERENCED_TABLE_NAME AND
k1.COLUMN_NAME = k2.REFERENCED_COLUMN_NAME AND
k1.TABLE_SCHEMA = k2.REFERENCED_TABLE_SCHEMA
)
SELECT *
FROM cte;
This assumes that user3
is the starting most parent table, with a primary key column of id
. The recursive CTE then builds out the chain of foreign keys. I also have assumed that your schema would be fixed.