Mysql8 遞歸查詢

Mysql8以上支持遞歸查詢了sql

1.構造表

DROP TABLE IF EXISTS `t_area`;
CREATE TABLE `t_area` (
  `id` int(11)  NOT NULL AUTO_INCREMENT,
  `name` char(64)  NOT NULL DEFAULT 0 COMMENT '名稱',
  `p_id` int(11)  NOT NULL DEFAULT 0 COMMENT '父id',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='test';

insert into t_area (id,name, p_id) VALUES (1,'中國',0),(2,'廣西省',1),(3,'廣東省',1),(4,'廣州市',3),(5,'深圳市',3),(6,'白雲區',4),(7,'越秀區',4),(8,'福田區',5),(9,'南山區',5);

2.遞歸查詢sql

with recursive  t as(
  select * from t_area  where id=3
  union all 
  select c.* from t_area c join t on c.p_id = t.id
)
select *from t;

3.實測

image

相關文章
相關標籤/搜索