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