mysql递归查询-案例(1)

 原始数据:id,parent_id:父id。

SET NAMES utf8mb4;

DROP TABLE IF EXISTS `t_city`;
CREATE TABLE `t_city` (
`id` int(0) NOT NULL,
`parent_id` int(0) NULL DEFAULT NULL,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

INSERT INTO `t_city` VALUES (1, 0, 'a');
INSERT INTO `t_city` VALUES (2, 0, 'b');
INSERT INTO `t_city` VALUES (3, 0, 'c');
INSERT INTO `t_city` VALUES (4, 1, 'a1');
INSERT INTO `t_city` VALUES (5, 1, 'a2');
INSERT INTO `t_city` VALUES (6, 2, 'a21');
INSERT INTO `t_city` VALUES (7, 3, 'c1');
INSERT INTO `t_city` VALUES (8, 7, 'c11');
INSERT INTO `t_city` VALUES (9, 7, 'c12');
INSERT INTO `t_city` VALUES (10, 8, 'c11-1');
INSERT INTO `t_city` VALUES (11, 9, 'c12-1');

 说明:

*、parent_id为0,表示为根目录。

WITH RECURSIVE cte_city AS(
SELECT * FROM t_city WHERE NAME = 'c'
UNION ALL
SELECT u.* FROM t_city u, cte_city t WHERE u.parent_id = t.id
)
SELECT * FROM cte_city;

  *、查询c部门下面的所有子部分。

 

WITH RECURSIVE cte_city AS(
SELECT * FROM t_city WHERE NAME = 'c12'
UNION ALL
SELECT u.* FROM t_city u, cte_city t WHERE u.id = t.parent_id
)
SELECT * FROM cte_city;

 *、查询:名称为c12的部门及上级部门。

 

*、多级目录查询(查询出所有“3”号分类下的所有子分类,并且分类名称带上上级分类的名称):

with recursive type_cte as (
    select id,name,parent_id  from t_city  where id = 3
    union all
    select t.id,concat(type_cte2.name,'>',t.name),t.parent_id 
    from t_city t
        inner join type_cte type_cte2 on t.parent_id = type_cte2.id
)
select id, name, parent_id
from type_cte;

 

*、 查询分类的所有父级分类

with recursive type_cte as (
    select id,name,parent_id  from t_city  where id = 8
    union all
    select t.id,concat(type_cte2.name,'>',t.name),t.parent_id
    from t_city t
             inner join type_cte type_cte2 on t.id = type_cte2.parent_id
)
select id, name, parent_id
from type_cte;

 

posted @ 2022-09-16 23:14  xiaoyongdata  阅读(87)  评论(0编辑  收藏  举报