MySQL8使用with recursive实现递归

MySQL8使用with recursive实现递归

语法
WITH recursive 表名 AS ( 
	初始语句(非递归部分) 
	UNION ALL 
	递归部分语句
)
[ SELECT| INSERT | UPDATE | DELETE]
案例
1.输出1 ~ n
WITH recursive t AS 
(
	SELECT 1 AS n 
	UNION ALL 
	SELECT n + 1 FROM t WHERE n < 10
) 
SELECT * FROM	t;
结果

MySQL8使用with recursive实现递归_第1张图片

2.输出n的阶乘
WITH recursive t AS (
	SELECT 1 AS n, 1 AS factorial 
	UNION ALL
	SELECT n + 1,	( n + 1 ) * factorial FROM t WHERE n < 10 
)
SELECT * FROM	t;
结果

MySQL8使用with recursive实现递归_第2张图片

3.输出前n项和
WITH recursive t AS ( 
	SELECT 1 AS n, 1 AS sum 
	UNION ALL 
	SELECT n + 1, n + 1 + sum FROM t WHERE n < 10 
) 
SELECT * FROM	t;
结果

MySQL8使用with recursive实现递归_第3张图片

你可能感兴趣的:(SQL,mysql,recursion)