首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >mysql 8.0中 树形数据的查询

mysql 8.0中 树形数据的查询

作者头像
鱼找水需要时间
发布2023-02-16 19:53:50
发布2023-02-16 19:53:50
3.1K00
代码可运行
举报
文章被收录于专栏:SpringBoot教程SpringBoot教程
运行总次数:0
代码可运行

mysql5.7中树形数据的查询

文章目录

代码语言:txt
复制
- [数据准备](https://cloud.tencent.com/developer)
- [自顶向下查询子树](https://cloud.tencent.com/developer)
- [自底向上查找所有节点](https://cloud.tencent.com/developer)
- [根据子节点id向上查找](https://cloud.tencent.com/developer)
代码语言:javascript
代码运行次数:0
运行
复制
WITH recursive 表名 AS ( 
	初始语句(非递归部分) 
	UNION ALL 
	递归部分语句
)
[ SELECT| INSERT | UPDATE | DELETE]

数据准备

代码语言:javascript
代码运行次数:0
运行
复制
-- ----------------------------
-- Table structure for tree
-- ----------------------------
DROP TABLE IF EXISTS `tree`;
CREATE TABLE `tree` (
  `id` int NOT NULL,
  `p_id` int DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tree
-- ----------------------------
BEGIN;
INSERT INTO `tree` VALUES (1, NULL, 'A');
INSERT INTO `tree` VALUES (2, NULL, 'B');
INSERT INTO `tree` VALUES (3, 1, 'A3');
INSERT INTO `tree` VALUES (4, 1, 'A4');
INSERT INTO `tree` VALUES (5, 2, 'B5');
INSERT INTO `tree` VALUES (6, 2, 'B6');
INSERT INTO `tree` VALUES (7, 2, 'B7');
INSERT INTO `tree` VALUES (8, 3, 'A3-8');
INSERT INTO `tree` VALUES (9, 3, 'A3-9');
INSERT INTO `tree` VALUES (10, 3, 'A3-10');
INSERT INTO `tree` VALUES (11, 4, 'A4-11');
INSERT INTO `tree` VALUES (12, 4, 'A4-12');
INSERT INTO `tree` VALUES (13, 6, 'B6-13');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

自顶向下查询子树

代码语言:javascript
代码运行次数:0
运行
复制
with RECURSIVE 
full_tree (id, p_id, name) AS
(select id, p_id, name from tree where p_id is null -- 查询条件
union all
select t.id, t.p_id, t.name from tree t
inner join full_tree on full_tree.id = t.p_id)
select * from full_tree;

查询结果:

自底向上查找所有节点

代码语言:javascript
代码运行次数:0
运行
复制
with RECURSIVE 
filter_tree (id, p_id, name) AS
(select id, p_id, name from tree where name like 'B%' -- 过滤条件
union all
select t.id, t.p_id, t.name from tree t
inner join filter_tree on filter_tree.p_id = t.id)
select distinct * from filter_tree;

查询结果:

根据子节点id向上查找

代码语言:javascript
代码运行次数:0
运行
复制
with RECURSIVE 
filter_tree (id, p_id, name) AS
(select id, p_id, name from tree where  id=13 -- 过滤条件
union all
select t.id, t.p_id, t.name from tree t
inner join filter_tree on filter_tree.p_id = t.id)
select distinct * from filter_tree;

查询结果:

参考文档

Spring整合常用组件

到此,本章内容就介绍完啦

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-09-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 数据准备
  • 自顶向下查询子树
  • 自底向上查找所有节点
  • 根据子节点id向上查找
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档