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

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

原创 aisql 2021-09-16
398

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

测试用构建起

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;
复制

8.0版本以前的写法 找出id = 4的所有父节点

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

8.0新特性 公用表达式写法 找出id = 4的所有父节点

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

结果展示
id name parid
4 1-1-1-1 3
3 1-1-1 2
2 1-1 1
1 1 0

mysql 递归写法大概就这两种。

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

评论