I have a MySQL table with the structure below (around 1 million rows).
Let's say I have two id's (X
and Y
), how could I check efficiently if X
is a child (any level) of Y
, or vice versa? My MySQL server version is 5.7.
Pseudo-code
IF X is child of Y:
SELECT hierarchy from Y to X
ELSE IF Y is child of X:
SELECT hierarchy from X to Y
ELSE:
SELECT nothing
Database structure
parent_id | child_id | child_level
----------------------------------
1 | 5 | 1
1 | 6 | 1
1 | 2 | 1
2 | 7 | 2
2 | 8 | 2
2 | 9 | 2
2 | 4 | 2
2 | 3 | 2
3 | 10 | 3
3 | 11 | 3
4 | 12 | 3
4 | 13 | 3
4 | 14 | 3