如何从父子关系从单个表中获取完整的家族id

7cjasjjr  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(303)

我有一个mysql表(族),如下所示

id parent_id 
4   null
5   4 
6   null 
7   null
36  5 
37  6

当我经过这里

id as 4 it should return 4 -5 - 36 
id as 5 it should return 4 -5 - 36 
id as 6 it should return 6 - 37 
id as 7 it should return 7
id as 36 it should return 4 -5 - 36 
id as 37 it should return 37 - 6 

SELECT t1.id AS lev1, t2.id as lev2, t3.id as lev3, t4.id as lev4
FROM family AS t1
LEFT JOIN family AS t2 ON t2.parent_id = t1.id
LEFT JOIN family AS t3 ON t3.parent_id = t2.id
LEFT JOIN family AS t4 ON t4.parent_id = t3.id
WHERE t1.id =5;

但是这个代码在某些情况下是失败的。有人能帮我吗?

xeufq47z

xeufq47z1#

根据提供的内容,我可以看到36和37不会返回您期望的值。
t1.id=36
t2.parent\u id应该=36,但没有一个这样做。
另外,“失败”是相当含糊不清的,是有错误还是你得到了一个不同于你预期的结果?如果是后者,可能是你预期的结果不对。

相关问题