'How to Recursively Query Referential Constraints in MySQl 8.0.23?
I am trying to write a recursive query in MySql 8.0.23 to return direct and indirect foreign key relationships pointing to a specified table. Beginning with table T1, the result set should reveal that each of T2 and T3 point to T1 (via an established constraint), that T4 points to T2, that T5 and T6 point to T3, etc.
Following is the query I'm using, which hangs / seems to runaway forever:
WITH RECURSIVE CTE AS (
SELECT REFERENTIAL_CONSTRAINTS.REFERENCED_TABLE_NAME, REFERENTIAL_CONSTRAINTS.TABLE_NAME, 0 AS DEPTH
FROM information_schema.REFERENTIAL_CONSTRAINTS
WHERE REFERENTIAL_CONSTRAINTS.CONSTRAINT_SCHEMA = 'MY_SCHEMA' AND REFERENTIAL_CONSTRAINTS.REFERENCED_TABLE_NAME = 'TABLE_A'
UNION ALL
SELECT REFERENTIAL_CONSTRAINTS.REFERENCED_TABLE_NAME, REFERENTIAL_CONSTRAINTS.TABLE_NAME, CTE.DEPTH + 1
FROM CTE
INNER JOIN information_schema.REFERENTIAL_CONSTRAINTS ON CTE.TABLE_NAME = REFERENTIAL_CONSTRAINTS.REFERENCED_TABLE_NAME
)
SELECT *
FROM CTE;
I would appreciate any advice on what I'm doing wrong. Thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
