MySQL根据子节点id查询所有父节点

数据表的结构:
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

你可能感兴趣的:(MySQL,Java开发心得,Mysql查询父节点,mysal)