码迷,mamicode.com
首页 > 数据库 > 详细

单纯MYSQL递归查询上下级关系

时间:2019-07-07 09:46:36      阅读:350      评论:0      收藏:0      [点我收藏+]

标签:sele   not   level   sql递归查询   递归   关系   group   rom   cat   

查询 id = 6 的所有父级

SELECT ID.level, DATA.* FROM( 
SELECT 
@id as _id, 
( SELECT @id := parent_id 
FROM table1 
WHERE id = @id 
) as _pid, 
@l := @l+1 as level 
FROM table1, 
(SELECT @id := 6, @l := 0 ) b 
WHERE @id > 0 
) ID, table1 DATA 
WHERE ID._id = DATA.id 
ORDER BY level;

根据这个父级查询方法,很容易可以写出查所有子级的,下面的查询 id=3 的所有子级
SELECT ID.level, DATA.* FROM( 
SELECT 
@ids as _ids, 
( SELECT @ids := GROUP_CONCAT(id) 
FROM table1 
WHERE FIND_IN_SET(parent_id, @ids) 
) as cids, 
@l := @l+1 as level 
FROM table1, 
(SELECT @ids :=3, @l := 0 ) b 
WHERE @ids IS NOT NULL 
) id, table1 DATA 
WHERE FIND_IN_SET(DATA.id, ID._ids) 
ORDER BY level, id

单纯MYSQL递归查询上下级关系

标签:sele   not   level   sql递归查询   递归   关系   group   rom   cat   

原文地址:https://www.cnblogs.com/hl15/p/11145058.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!