MySQL8 with recursive递归查询,实现查子集数据和父级数据


1、查询所有子集元素

概述

查出所有子集数据,以及子集的子集,子集的子集的子集,等等

注意:该语法从MySQL8开始支持

话不多述,直接上案例

构造表

  • 创建区域表,字段分别为id、父级id、区域名称
CREATE TABLE t_area  (
  id int(0) NOT NULL AUTO_INCREMENT,
  parent_id int(0) NULL DEFAULT NULL,
  name varchar(255) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

  • 数据初始化
INSERT INTO `t_area`(`id`, `parent_id`, `name`) VALUES (1, 0, '福建省');
INSERT INTO `t_area`(`id`, `parent_id`, `name`) VALUES (2, 1, '泉州市');
INSERT INTO `t_area`(`id`, `parent_id`, `name`) VALUES (3, 1, '福州市');
INSERT INTO `t_area`(`id`, `parent_id`, `name`) VALUES (4, 1, '厦门市');
INSERT INTO `t_area`(`id`, `parent_id`, `name`) VALUES (5, 2, '丰泽区');
INSERT INTO `t_area`(`id`, `parent_id`, `name`) VALUES (6, 2, '鲤城区');
INSERT INTO `t_area`(`id`, `parent_id`, `name`) VALUES (7, 4, '思明区');
INSERT INTO `t_area`(`id`, `parent_id`, `name`) VALUES (8, 4, '湖里区');
INSERT INTO `t_area`(`id`, `parent_id`, `name`) VALUES (9, 4, '翔安区');
INSERT INTO `t_area`(`id`, `parent_id`, `name`) VALUES (10, 7, '莲前街道');

查询结果

  • 需求:查询出厦门市底下所有区域
with recursive t as
(	
	select * from t_area where name = '厦门市'
	union all
	select a.* from t_area a join t on a.parent_id = t.id
)
select * from t
  • 结果如下。其中,莲前街道为思明区的子集,也会一起查询出来
    在这里插入图片描述

查询所有父级数据

概述

查出当前父级数据,以及父级的父级,父级的父级的父级,等等

语法

with recursive t as
(	
	select * from t_area where name = '莲前街道'
	union all
	select a.* from t_area a join t on a.id = t.parent_id
)
select * from t

结果如下

在这里插入图片描述


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM