您的位置:首页 > 数据库 > MySQL

mysql从子类id查询所有父类

2011-06-17 16:59 381 查看



mysql从子类id查询所有父类 收藏

表结构

view plaincopy to clipboardprint?

id name parent_id

---------------------------

1 Home 0

2 About 1

3 Contact 1

4 Legal 2

5 Privacy 4

6 Products 1

7 Support 1

mysql代码如下:

view plaincopy to clipboardprint?

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,

table1 h

WHERE @r <> 0) T1

JOIN table1 T2

ON T1._id = T2.id

ORDER BY T1.lvl DESC

代码@r := 5标示查询id为5的所有父类。结果如下

view plaincopy to clipboardprint?

1, 'Home'

2, 'About'

4, 'Legal'

5, 'Privacy'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息