mysql8递归查询

递归查询子元素

create table t_test(
	id varchar(64) not null primary key,
	name varchar(64),
	pid varchar(64)
);
INSERT INTO `t_test`(`id`, `name`, `pid`) VALUES ('1', '张三', '0');
INSERT INTO `t_test`(`id`, `name`, `pid`) VALUES ('2', '张三儿子', '1');
INSERT INTO `t_test`(`id`, `name`, `pid`) VALUES ('3', '张三孙子', '2');
INSERT INTO `t_test`(`id`, `name`, `pid`) VALUES ('4', '李四', '0');
INSERT INTO `t_test`(`id`, `name`, `pid`) VALUES ('5', '赵武', '0');
-- 把 张三 以及 张三的子孙查询出来
with recursive tmp as(
	select a.* from t_test a where a.name = '张三'
	union all
	select a.* from t_test a, tmp t where t.id = a.pid
)
select * from tmp;

递归查询时间段

with recursive date_range as (
	select '2022-02-02 00:00:00' as dateTime
	union all
	select dateTime + interval 1 day from date_range where dateTime < '2022-02-04 00:00:00'
)
select * from date_range

在这里插入图片描述
带参数写法:

with recursive date_range(jt_date) as (
select @num:='2022-08-11'
union all
select @num:=date_add(@num, interval 1 day) from date_range where jt_date < '2022-08-17'
)
select * from  date_range;

在这里插入图片描述

interval 1 day : 间隔一天
interval 1 hour : 间隔一小时
interval 1 minute : 间隔一分钟
interval 1 second : 间隔一秒钟

平方数列

with recursive square(x, f) as(
	select 1, 1
	union all
	select x + 1, (x + 1) * (x + 1) from square where x < 8
)
select * from square;

在这里插入图片描述

斐波那契数列

方法定义:F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=3,n∈N*)

with recursive fibonacci(x, f1, f2) as(
	select 1, 1, 1
	union all
	select x + 1, f2, f1 + f2 from fibonacci where x < 8
)
select x, f1, f2 from fibonacci;

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_26264237

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值