且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取父子层次结构

更新时间:2023-12-04 19:04:04

WITH RECURSIVE
cte AS (
SELECT *, 0 level, '      ' relation
FROM dogs
WHERE dog_id = 7

UNION ALL

SELECT dogs.*, level + 1, 'father'
FROM dogs
JOIN cte ON cte.father_id = dogs.dog_id
WHERE level < 5

UNION ALL

SELECT dogs.*, level + 1, 'mother'
FROM dogs
JOIN cte ON cte.mother_id = dogs.dog_id
WHERE level < 5
)
SELECT *
FROM cte
ORDER BY level, relation;

小提琴

结果

dog_id | name     | father_id | mother_id | level | relation
-----: | :------- | --------: | --------: | ----: | :-------
     7 | GrandSon |         5 |         6 |     0 |         
     5 | Son      |         1 |         2 |     1 | father  
     6 | Daughter |         3 |         4 |     1 | mother  
     1 | Father   |      null |      null |     2 | father  
     3 | Father1  |      null |      null |     2 | father  
     2 | Mother   |      null |      null |     2 | mother  
     4 | Mother2  |      null |      null |     2 | mother