mysql 8.0中 树形数据的查询
  TEZNKK3IfmPf 2023年11月12日 40 0

​​mysql5.7中树形数据的查询​​

WITH recursive 表名 AS ( 
初始语句(非递归部分)
UNION ALL
递归部分语句
)
[ SELECT| INSERT | UPDATE | DELETE]

数据准备

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

自顶向下查询子树

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;

查询结果:

mysql 8.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;

查询结果:

mysql 8.0中 树形数据的查询

根据子节点id向上查找

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;

查询结果:

mysql 8.0中 树形数据的查询

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

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月12日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   27   0   0 mysql
  TEZNKK3IfmPf   2024年05月17日   54   0   0 sqlmysql
  TEZNKK3IfmPf   2024年05月31日   31   0   0 数据库mysql
  TEZNKK3IfmPf   2024年05月17日   50   0   0 查询mysql索引
  TEZNKK3IfmPf   2024年05月17日   50   0   0 jsonmysql
  TEZNKK3IfmPf   2024年05月17日   50   0   0 mysqlphp
  TEZNKK3IfmPf   2024年05月31日   27   0   0 数据库mysql
TEZNKK3IfmPf