mysql递归查询从子类ID查询所有父类
先来看数据表的结构如下:
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
我要的要求是根据一个分类ID(这个分类ID可能是一个子分类),得到所有的父分类,下面是相应的SQL:
方式一:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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 <> 2 union all select @r, parent_id,@l+1 FROM table1 WHERE id = @r ) T1 JOIN table1 T2 ON T1._id = T2.id ORDER BY T1.lvl DESC |
方式二:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
SELECT T2.id, T2. name FROM ( SELECT @r AS _id, @stop:=@stop+if(@r=2,1,@stop) as stop, ( SELECT @r := parent_id FROM table1 WHERE id = _id) AS parent_id, @l := @l + 1 AS lvl FROM ( SELECT @r := 5, @l := 0, @stop:=0) vars, table1 h WHERE @stop < 1) T1 JOIN table1 T2 ON T1._id = T2.id ORDER BY T1.lvl DESC |