mysql8 用数字区间生成连续数字 并 连接其他表
1. 业务场景
用户输入起止号牌,查看号牌使用情况。
例如用户输入300至400的号牌,数据库生成300、301、302…399、400这样的连续数字,并且用这些连续数字,连接其他业务表,查看该号牌的使用状态
2. 解决方案
with recursive c(n) AS
(
select 号段起
union ALL
select n + 1
from c
where n < 号段止
)
select c.n hd
from c
left join c_flow f on f.hphm = c.n
order by c.n asc
请注意:
1)、with recursive c(n) AS 是 mysql8语法
2)、号段止,虽然用的小于号,不是小于等于,但是也包括这个结束值,例如刚才 300~400,那400是会显示出来的。
以下是生成连续数字的关键语法。
with recursive c(n) AS
(
select 号段起
union ALL
select n + 1
from c
where n < 号段止
)
select c.n hd
from c
如果连其他表以后,想显示这个连续数字及其他表的字段,写在下面圈起来的位置