MySQL根据子节点id查询所有父节点
数据表的结构:idnameparent_id---------------------------Home0About1Contact1Legal2Privacy4Products1Support1SELECT T2.id, T2.nam...
·
数据表的结构:
id name parent_id
---------------------------
Home 0
About 1
Contact 1
Legal 2
Privacy 4
Products 1
Support 1
SELECT T2.id, T2.name
FROM (
SELECT
@r AS _id,
(SELECT @r := parent_id FROM table1 WHERE id = _id) AS parent_id,
@l := @l + 1 AS lvl
FROM
(SELECT @r := 5, @l := 0) vars, --查询id为5的所有上级
table1 h
WHERE @r <> 0) T1
JOIN table1 T2
ON T1._id = T2.id
ORDER BY T1.lvl DESC
更多推荐
已为社区贡献3条内容
所有评论(0)