我创建了一个名为“net”的表,并插入了这样的值。
id name parent
--------------------------------------
1 fruits 0
2 Apple 1
3 Orange 1
4 Grape 2
5 Green Apple 2
6 Red Apple 4
我想让孩子的所有父母“6”。请帮帮我
我期待的结果,当过滤数据时,id = 6,它将生成我期待的结果。
lv1 lv2 lv3
--------------------------------------
4 2 1
或者像这样
id name parent
--------------------------------------
4 Grape 2
2 Apple 1
1 fruits 0
答案 0 :(得分:2)
您可以使用:
SELECT T2.id, T2.name, T2.parent
FROM (
SELECT
@r AS _id,
(SELECT @r := parent FROM table1 WHERE id = _id) AS parent,
@l := @l + 1 AS lvl
FROM
(SELECT @r := 6, @l := 0) vars,
table1 h
WHERE @r <> 0) T1
JOIN table1 T2
ON T1._id = T2.id
where T2.id<>6
ORDER BY T1.lvl