mysql8.0版本递归查询

Posted 颂先生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql8.0版本递归查询相关的知识,希望对你有一定的参考价值。

1.先在mysql数据库添加数据

DROP TABLE IF EXISTS `dept`;
CREATE TABLE `dept`  (
  `id` int(11) NOT NULL,
  `pid` int(11) DEFAULT NULL,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `date` datetime(0) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of dept
-- ----------------------------
INSERT INTO `dept` VALUES (1, 0, \'总部门\', \'2020-04-16 15:00:54\');
INSERT INTO `dept` VALUES (2, 1, \'课程部\', \'2020-04-16 15:00:57\');
INSERT INTO `dept` VALUES (3, 1, \'爱好部\', \'2020-04-16 15:01:01\');
INSERT INTO `dept` VALUES (4, 1, \'小吃部\', \'2020-04-16 15:01:03\');
INSERT INTO `dept` VALUES (5, 2, \'语文\', \'2020-04-15 15:01:07\');
INSERT INTO `dept` VALUES (6, 3, \'羽毛球\', \'2020-04-15 15:01:14\');
INSERT INTO `dept` VALUES (7, 4, \'臭豆腐\', \'2020-04-15 15:01:18\');
INSERT INTO `dept` VALUES (8, 4, \'鸭脖\', \'2020-07-11 11:21:29\');

 

根据父级Id递归查询所有子节点(查询父级Id为0 并且分类为0的所有子节点)

WITH RECURSIVE cte AS
(
SELECT a.id, a.pid,a.name FROM dept a WHERE a.id=\'1\'
UNION ALL
SELECT k.id, k.pid,k.name FROM dept k INNER JOIN cte c ON c.id = k.pid
)SELECT id,name,pid FROM cte

 

根据子节点查询所有父亲节点(查询子节点Id为8的所有父节点)


WITH RECURSIVE cte AS
(
SELECT a.id, a.pid,a.name FROM dept a WHERE a.id=\'8\'
UNION ALL
SELECT k.id, k.pid,k.name FROM dept k INNER JOIN cte c ON c.pid = k.id
)SELECT id,name,pid FROM cte

 

 

 

二.sqlserver 的查询语句写法(去掉RECURSIVE即可 当然得在sqlserver数据库中添加数据 并执行语句)

 

WITH cte AS
(
SELECT a.id, a.pid,a.name FROM dept a WHERE a.id=\'4\'
UNION ALL
SELECT k.id, k.pid,k.name FROM dept k INNER JOIN cte c ON c.id = k.pid
)SELECT id,name,pid FROM cte

 

 

原文参考:https://www.cnblogs.com/liuxiaoji/p/11152094.html

 

以上是关于mysql8.0版本递归查询的主要内容,如果未能解决你的问题,请参考以下文章

Mysql8.0递归函数

MySQL基础--09---MySQL8新特性简述----公用表表达式

MySQL怎样做递归查询

Sql ServerSQL SERVER 递归查询

mysql递归查询cte

SQLAlchemy 递归查询结果集排序