tableA包含{id,fromPos not null,toPos}
并具有以下值
tableA (1, 5) // means any position greater than or equal to 5
tableA (2, 5, 10) // means any position between 5 and 10 (inclusive)
tableA (3, 6)
tableA (4, 7, 9)
答案 0 :(得分:3)
select *
from tableA t
where t.fromPos <= requested_position
and coalesce(t.toPos, requested_position) >= requested_position
Coalesce
表示如果requested_position
似乎为空,则会t.toPos
进行比较,因此,比较将始终为真,您只会处理t.fromPos <= requested_position
或者,您可以使用between
以获得更好的可读性,这是相同的:
select *
from tableA t
where requested_position between t.fromPos and coalesce(t.toPos, requested_position)
答案 1 :(得分:2)
对于给定的目标值X,查询似乎是:
SELECT id
FROM TableA
WHERE fromPos <= X
AND (toPos >= X OR toPos IS NULL);
答案 2 :(得分:2)
declare @position int
set @position = 8
select id from tablea
where @position >= fromPos
and (@position <= toPos or toPos is null)
create table tableA
(
id int not null,
fromPos int not null,
toPos int null
)
insert into dbo.tableA(id, fromPos) values (1, 5)
insert into dbo.tableA(id, fromPos, toPos) values (2, 5, 10)
insert into dbo.tableA(id, fromPos) values (3, 6)
insert into dbo.tableA(id, fromPos, toPos) values (4, 7, 9)
答案 3 :(得分:0)
假设当您的示例中没有提到toPos时,它将为null。
1. Select * from tableA where fromPos <= 7 and (toPos=null or toPos >= 7)
2. Select * from tableA where fromPos <= 5 and (toPos=null or toPos >= 5)
3. Select * from tableA where fromPos <= 8 and (toPos=null or toPos >= 8)
答案 4 :(得分:0)
SELECT id
FROM <table>
WHERE <value> BETWEEN fromPos AND COALESCE(toPos,99999999)