Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

一张表结构如下,省略其他字段,start和end字段是数字,只保证end大于start

idstartend
1111222
2232242
3xx+N

需求是我需要通过这张表的(start,end)去其他表中查询出对应的记录,但是其他表中可能会存在(start,end)中有记录不存在的情况,但是我需要将不存在的情况也考虑,希望查询结果如下:

id
start
start+1
start+n
start+ ...
end

如何通过sql将(start,end)区间中的每一个数字都查询成为一条记录,这样就可以通过这个去左连接其他表

目前已知一个办法是

select (
    select start
    union
    select start +1 
    union
    select start + ...
    union
    select end
)left join xxx 。。。。。。

想请问下有没有更好的办法


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

分步查询:
将start和end作为查询条件
eg:select * from 本表 where id=? 得到对应id的start值和end值
将值带入:
select * from 左连接的表 where id>start and id <end


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...