mysql 8.0 树形数据的查询
Posted isea533
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql 8.0 树形数据的查询相关的知识,希望对你有一定的参考价值。
参考文档
测试数据
-- ----------------------------
-- Table structure for tree
-- ----------------------------
DROP TABLE IF EXISTS `tree`;
CREATE TABLE `tree` (
`id` int NOT NULL,
`p_id` int DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tree
-- ----------------------------
BEGIN;
INSERT INTO `tree` VALUES (1, NULL, 'A');
INSERT INTO `tree` VALUES (2, NULL, 'B');
INSERT INTO `tree` VALUES (3, 1, 'A3');
INSERT INTO `tree` VALUES (4, 1, 'A4');
INSERT INTO `tree` VALUES (5, 2, 'B5');
INSERT INTO `tree` VALUES (6, 2, 'B6');
INSERT INTO `tree` VALUES (7, 2, 'B7');
INSERT INTO `tree` VALUES (8, 3, 'A3-8');
INSERT INTO `tree` VALUES (9, 3, 'A3-9');
INSERT INTO `tree` VALUES (10, 3, 'A3-10');
INSERT INTO `tree` VALUES (11, 4, 'A4-11');
INSERT INTO `tree` VALUES (12, 4, 'A4-12');
INSERT INTO `tree` VALUES (13, 6, 'B6-13');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
自顶向下查询子树
with RECURSIVE
full_tree (id, p_id, name) AS
(select id, p_id, name from tree where p_id is null -- 查询条件
union all
select t.id, t.p_id, t.name from tree t
inner join full_tree on full_tree.id = t.p_id)
select * from full_tree;
查询结果:
+----+------+-------+
| id | p_id | name |
+----+------+-------+
| 1 | NULL | A |
| 2 | NULL | B |
| 3 | 1 | A3 |
| 4 | 1 | A4 |
| 5 | 2 | B5 |
| 6 | 2 | B6 |
| 7 | 2 | B7 |
| 8 | 3 | A3-8 |
| 9 | 3 | A3-9 |
| 10 | 3 | A3-10 |
| 11 | 4 | A4-11 |
| 12 | 4 | A4-12 |
| 13 | 6 | B6-13 |
+----+------+-------+
自底向上查找所有节点
with RECURSIVE
filter_tree (id, p_id, name) AS
(select id, p_id, name from tree where name like 'B%' -- 过滤条件
union all
select t.id, t.p_id, t.name from tree t
inner join filter_tree on filter_tree.p_id = t.id)
select distinct * from filter_tree;
查询结果:
+----+------+-------+
| id | p_id | name |
+----+------+-------+
| 2 | NULL | B |
| 5 | 2 | B5 |
| 6 | 2 | B6 |
| 7 | 2 | B7 |
| 13 | 6 | B6-13 |
+----+------+-------+
以上是关于mysql 8.0 树形数据的查询的主要内容,如果未能解决你的问题,请参考以下文章