mysql:递归查询

2022/9/18 2:16:25

本文主要是介绍mysql:递归查询,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 原始数据: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;

 



这篇关于mysql:递归查询的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程