上一篇内容,通过MySQL存储过程实现累加运算 1+2+...+n 等于多少的需求,使用当前主流版本MySQL5.7.x 和MySQL8.0.x,以及最新的MySQL8.4 LST版本。
WITH AS子句在MySQL 8.0.x及更高版本中得到支持,而在MySQL 5.7及以下版本中则不支持。
参考地址如下:
https://blog.csdn.net/zxrhhm/article/details/139185014?spm=1001.2014.3001.5501
1、本文内容
MySQL8.0新特性CTE(Common Table Expressions)的子句表达式,递归实现累加运算 1+2+...+n 等于多少?
sql
(root@192.168.80.85)[superdb]> select @@version;
+-----------+
| @@version |
+-----------+
| 8.4.0 |
+-----------+
1 row in set (0.00 sec)
-- 定义一个cte recursive 公用表达式t_sumtest
-- num_sum 列标识计算的和
-- last_num 列标识当前数的前一个数值
-- current_num 列标识当前数的值
(root@192.168.80.85)[superdb]> WITH recursive t_sumtest (num_sum,last_num,current_num) as
-> ( SELECT 1,0,1 FROM DUAL
-> UNION ALL
-> SELECT t1.num_sum+t1.last_num,t1.num_sum,t1.current_num+1 FROM t_sumtest t1 WHERE t1.current_num<10
-> )
-> SELECT num_sum,last_num,current_num FROM t_sumtest;
+---------+----------+-------------+
| num_sum | last_num | current_num |
+---------+----------+-------------+
| 1 | 0 | 1 |
| 1 | 1 | 2 |
| 2 | 1 | 3 |
| 3 | 2 | 4 |
| 5 | 3 | 5 |
| 8 | 5 | 6 |
| 13 | 8 | 7 |
| 21 | 13 | 8 |
| 34 | 21 | 9 |
| 55 | 34 | 10 |
+---------+----------+-------------+
10 rows in set (0.00 sec)
(root@192.168.80.85)[superdb]> WITH recursive t_sumtest (num_sum,last_num,current_num) as
-> ( SELECT 1,0,1 FROM DUAL
-> UNION ALL
-> SELECT t1.num_sum+t1.last_num,t1.num_sum,t1.current_num+1 FROM t_sumtest t1 WHERE t1.current_num<10
-> )
-> SELECT num_sum,last_num,current_num FROM t_sumtest where current_num=10;
+---------+----------+-------------+
| num_sum | last_num | current_num |
+---------+----------+-------------+
| 55 | 34 | 10 |
+---------+----------+-------------+
1 row in set (0.01 sec)