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

更多推荐