Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何编写sql查询以确定值是否在某个范围内_Sql_Mysql - Fatal编程技术网

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

如何编写sql查询以确定值是否在某个范围内,sql,mysql,Sql,Mysql,表A包含{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)

表A包含{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)

假设在您的示例中没有提到地形,则该地形将为空

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)
1。从表格A中选择*,其中fromPos=7)
2.从表格A中选择*,其中fromPos=5)
3.从表格A中选择*,其中fromPos=8)
选择id
从…起
其中fromPos和COALESCE之间(toPos,9999999)

对于给定的目标值X,查询似乎是:

SELECT id
  FROM TableA
 WHERE fromPos <= X
   AND (toPos >= X OR toPos IS NULL);
选择id
从表格
其中fromPos=X或toPos为空);
声明@position int
设置@位置=8
从表A中选择id
其中@position>=fromPos

和(@位置你说的那张桌子(1,5)表示位置大于5。但您也说,获取位置为5的条目时应返回1,2。这不矛盾吗?它包含在内,将改变comments@Jonthan抱歉,我犯了一个错误。更正的itID=1应该被选为位置8erhm,你的描述和示例结果仍然是错误的,我想?7不是比7大吗6(第3行)?在标准SQL中不能使用“toPos=NULL”:必须使用“toPos IS NULL”。he can use SET ANSIU NULLS是off表名,当搜索的值为1亿或更大时,一般解决方案不应崩溃。可以正常工作,但使用ISNULL()或COALESCE()在这种情况下,出于性能原因,应避免在大型表上使用筛选器
SELECT id
  FROM TableA
 WHERE fromPos <= X
   AND (toPos >= X OR toPos IS NULL);
select * 
  from tableA t
 where t.fromPos <= requested_position
   and coalesce(t.toPos, requested_position) >= requested_position
select * 
  from tableA t
 where requested_position between t.fromPos and coalesce(t.toPos, requested_position)
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)