日期: 2020-06-23 16:28:06
之前写过一篇 MySQL通过自定义函数的方式,递归查询树结构,从MySQL 8.0 开始终于支持了递归查询的语法
CTE
首先了解一下什么是 CTE,全名 Common Table Expressions
WITH cte1 AS (SELECT a, b FROM table1), cte2 AS (SELECT c, d FROM table2) SELECT b, d FROM cte1 JOIN cte2 WHERE cte1.a = cte2.c;
cte1, cte2 为我们定义的CTE,可以在当前查询中引用
可以看出 CTE 就是一个临时结果集,和派生表类似,二者的区别这里不细说,可以参考下MySQL开发文档:https://dev.mysql.com/doc/refman/8.0/en/with.html#common-table-expressions-recursive-examples
递归查询
先来看下递归查询的语法
WITH RECURSIVE cte_name AS ( SELECT ... -- return initial row set UNION ALL / UNION DISTINCT SELECT ... -- return additional row sets ) SELECT * FROM cte;
递归部分不能包括:
上面的讲解可能有点抽象,通过例子慢慢来理解
WITH RECURSIVE cte (n) AS -- 这里定义的n相当于结果集的列名,也可在下面查询中定义 ( SELECT 1 UNION ALL SELECT n + 1 FROM cte WHERE n < 5 ) SELECT * FROM cte; -- result +------+ | n | +------+ | 1 | | 2 | | 3 | | 4 | | 5 | +------+
EXAMPLE
最后来看一个树结构的例子
CREATE TABLE `c_tree` ( `id` int(11) NOT NULL AUTO_INCREMENT, `cname` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `parent_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
mysql> select * from c_tree; +----+---------+-----------+ | id | cname | parent_id | +----+---------+-----------+ | 1 | 1 | 0 | | 2 | 2 | 0 | | 3 | 3 | 0 | | 4 | 1-1 | 1 | | 5 | 1-2 | 1 | | 6 | 2-1 | 2 | | 7 | 2-2 | 2 | | 8 | 3-1 | 3 | | 9 | 3-1-1 | 8 | | 10 | 3-1-2 | 8 | | 11 | 3-1-1-1 | 9 | | 12 | 3-2 | 3 | +----+---------+-----------+
mysql> WITH RECURSIVE tree_cte as ( select * from c_tree where parent_id = 3 UNION ALL select t.* from c_tree t inner join tree_cte tcte on t.parent_id = tcte.id ) SELECT * FROM tree_cte; +----+---------+-----------+ | id | cname | parent_id | +----+---------+-----------+ | 8 | 3-1 | 3 | | 12 | 3-2 | 3 | | 9 | 3-1-1 | 8 | | 10 | 3-1-2 | 8 | | 11 | 3-1-1-1 | 9 | +----+---------+-----------+
更多信息
https://dev.mysql.com/doc/refman/8.0/en/with.html
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持奥多码。
上一篇:mysql存储过程之创建(CREATE PROCEDURE)和调用(CALL)及变量创建(DECLARE)和赋值(SET)操作方法