SQL 检查 Integer 是否在一系列列值之间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29143988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if Integer is between a range of column values
提问by Dan
Consider the following table schema:
考虑以下表架构:
----------------------------------
| ID | MinValue | MaxValue |
----------------------------------
| 1 | 0 | 10 |
| 2 | 11 | 20 |
| 3 | 21 | 30 |
I want to be able to pass an integer, and have it return the appropriate ID where that value matches the range between Min and Max Value.
我希望能够传递一个整数,并让它返回适当的 ID,其中该值与 Min 和 Max Value 之间的范围相匹配。
EG:
例如:
Input = 17
Output = 2
Input = 4
Output = 1
Input = 26
Output = 3
I thought I could do something like:
我以为我可以做这样的事情:
SELECT ID FROM MyTable WHERE MinValue >= @input AND MaxValue <= @input
But it doesn't work, nothing is returned.
但它不起作用,什么都没有返回。
I'm sure the solution is blatantly simple, but i'm stumped.
我确信解决方案非常简单,但我很难过。
What's the best way to achieve this in SQL Server?
在 SQL Server 中实现这一目标的最佳方法是什么?
回答by Imran Ali Khan
try this
尝试这个
SELECT ID FROM MyTable WHERE @input BETWEEN MinValue AND MaxValue
DESCRIPTION of BEETWEEN
之间的描述
The SQL BETWEEN
Condition is used to retrieve values within a range in a SELECT
, INSERT
, UPDATE
, or DELETE
statement.
该SQLBETWEEN
条件是用于在一个范围内检索值SELECT
,INSERT
,UPDATE
,或DELETE
语句。
SYNTAX
句法
The syntax for the SQL BETWEEN
Condition is:
SQLBETWEEN
条件的语法是:
expression BETWEEN value1 AND value2
;
Parameters or Arguments
表达BETWEEN value1 AND value2
;参数或参数
expression is a column or calculation.
表达式是列或计算。
value1
and value2
create an inclusive range that expression is compared to.
value1
并value2
创建一个与表达式进行比较的包含范围。
NOTE
笔记
The SQL BETWEEN
Condition will return the records where expression is within the range of value1
and value2
(inclusive).
SQLBETWEEN
条件将返回表达式在value1
和value2
(包括)范围内的记录。
ref: http://www.techonthenet.com/sql/between.php
参考:http: //www.techonthenet.com/sql/between.php
or you can also use like
或者你也可以使用像
MinValue <= @input AND MaxValue >= @input
回答by rhholt
Try this,
尝试这个,
SELECT ID FROM MyTable WHERE @input BETWEEN MinValue AND MaxValue.
Or flip the equality signs in your statement.
或者翻转语句中的等号。
SELECT ID FROM MyTable WHERE MinValue <= @input AND MaxValue >= @input
回答by Matt
Use BETWEEN
之间使用
SELECT ID
FROM MyTable
WHERE @input BETWEEN MinValue AND MaxValue