这篇文章主要介绍了MySql如何利用父id递归向下查询子节点,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
不用写存储过程,不用建数据库函数,一段sql就可以实现
SELECT ID.LEVEL, DATA.* FROM ( SELECT @ids AS _ids, ( SELECT @ids := GROUP_CONCAT( region_id ) FROM region WHERE FIND_IN_SET(parent_id, @ids ) ) AS cids, @l := @l + 1 AS LEVEL FROM region, ( SELECT @ids := 3, @l := 0 ) b WHERE @ids IS NOT NULL ) ID, region DATA WHERE FIND_IN_SET( DATA.region_id, ID._ids ) ORDER BY LEVEL
测试
--创建测试环境 create table t_test( id int PRIMARY key, parent_id int, name varchar(200) ) insert t_test VALUES(1,null,"中国"); insert t_test VALUES(2,1,"华北"); insert t_test VALUES(3,2,"山西省"); insert t_test VALUES(4,2,"北京"); insert t_test VALUES(5,3,"临汾市"); insert t_test VALUES(6,4,"北京市"); insert t_test VALUES(7,5,"尧都区"); insert t_test VALUES(8,6,"朝阳区"); insert t_test VALUES(9,7,"解放西路"); insert t_test VALUES(10,8,"朝阳北路"); SELECT * FROM t_test;
测试数据展示
查询 id=1,查询中国下边有哪些地方
SELECT ID.LEVEL, DATA.* FROM ( SELECT @ids AS _ids, ( SELECT @ids := GROUP_CONCAT( id ) FROM t_test WHERE FIND_IN_SET(parent_id, @ids ) ) AS cids, @l := @l + 1 AS LEVEL FROM t_test, ( SELECT @ids := 1, @l := 0 ) b WHERE @ids IS NOT NULL ) ID, t_test DATA WHERE FIND_IN_SET( DATA.id, ID._ids ) ORDER BY LEVEL
id=3,查询山西下边有哪些地方
SELECT ID.LEVEL, DATA.* FROM ( SELECT @ids AS _ids, ( SELECT @ids := GROUP_CONCAT( id ) FROM t_test WHERE FIND_IN_SET(parent_id, @ids ) ) AS cids, @l := @l + 1 AS LEVEL FROM t_test, ( SELECT @ids := 3, @l := 0 ) b WHERE @ids IS NOT NULL ) ID, t_test DATA WHERE FIND_IN_SET( DATA.id, ID._ids ) ORDER BY LEVEL
id=4,查询北京下边有哪些地方
最后再从 id=2 华北地区往下查询
感谢你能够认真阅读完这篇文章,希望小编分享的“MySql如何利用父id递归向下查询子节点”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。