如何编写SQL查询以确定值是否在一个范围内

时间:2010-09-08 10:59:22

标签: sql mysql

tableA包含{id,fromPos not null,toPos}

  • fromPos和toPos表示特定行的值范围
  • 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)
  • 如何获取位置为7的所有条目。它应返回id(1,2,3,4)
  • 如何获取位置为5的所有条目。它应返回id(1,2)
  • 如何获取位置为8的所有条目。它应该返回id(1,2,3,4)

5 个答案:

答案 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)