暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

mysql 5.x与8.0版本实现树型结构表递归 8.0用公用表达式可轻松实现(一)

原创 aisql 2021-09-16
375

实际业务中,我们经常会遇到树型结构的表设计,然后在查询中要求根据树的某一个节点,返回所有子节点或父节点
今天我们先来看看 SQL中使用递归实现找所有子结点

-- 构造测试数据2 CREATE TABLE `treetable` ( `id` int NOT NULL , `name` varchar(50) NOT NULL , `parid` int NOT NULL , PRIMARY KEY (`id`) ) ; insert into treetable select 1,'1',0 union all select 2,'1-1',1 union all select 3,'1-1-1',2 union all select 4,'1-1-1-1',3 union all select 5,'1-1-1-1-1',4;

找出 id = 2 的所有儿子(包含自身)
5.x写法

select * from (select id,name,if(parid = @a,@a := id,0) as hassum from treetable,(select @a := 2) as t1 order by parid ) as t where t.hassum !=0;

8.0写法

with RECURSIVE cte as ( select * from treetable where id = 2 union all select a.* from treetable a inner join cte b on a.parid = b.id ) select * from cte;

查询结果
id name parid
2 1-1 1
3 1-1-1 2
4 1-1-1-1 3
5 1-1-1-1-1 4

可见 用8.0的新特性 公用表达式 写起来清爽很多。

如果是查某个节点的所有父节点呢?

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论