MySQL8.0版本以上支持递归查询
CTE
WITH RECURSIVE cte_name[(col_name [, col_name] ...)] AS ( initial_query -- anchor member UNION ALL recursive_query -- recursive member that references to the CTE name ) SELECT * FROM cte_name;
UNION
、UNION ALL
或者UNION DISTINCT
运算符与锚成员相连。R0
),并使用该基本结果集进行下一次迭代。Ri
结果集作为输入执行递归成员,并将Ri+1
作为输出。UNION ALL
运算符将结果集从R0
到Rn
组合。WITH RECURSIVE seq_num(n) as ( select 1 UNION ALL select n+1 from seq_num where n < 10 ) select * from seq_num;
WITH RECURSIVE organ_rec (organCode,parentCode)as ( select organCode,parentCode from g_organ where organCode ='101.007.009.004.011' UNION ALL select g.organCode,g.parentCode from g_organ g INNER JOIN organ_rec on organ_rec.parentCode = g.organCode ) select organCode,parentCode from organ_rec;
WITH RECURSIVE organ_rec (organCode,parentCode)as ( select organCode,parentCode from g_organ where parentCode ='-1' UNION ALL select g.organCode,g.parentCode from g_organ g INNER JOIN organ_rec on organ_rec.organCode = g.parentCode ) select organCode,parentCode from organ_rec;
递归CTE的查询语句中需要包含一个终止递归查询的条件。当由于某种原因在递归CTE的查询语句中未设置终止条件时,MySQL会根据相应的配置信息,自动终止查询并抛出相应的错误信息。在MySQL中默认提供了如下两个配置项来终止递归CTE。
查看cte_max_recursion_depth参数的默认值,并设置。
--- 默认1000 SHOW VARIABLES LIKE 'cte_max%'; --- 会话级别设置该值 SET SESSION cte_max_recursion_depth=999999999;
查看MySQL中max_execution_time参数的默认值,并设置。
--- 0:表示没有限制 SHOW VARIABLES LIKE 'max_execution%'; ---单位为毫秒 SET SESSION max_execution_time=1000;
递归查询时,如果是由上往下查询时,建议通过类似层级码或者树型码字段,通过关键字 LIKE
查询。
参考: