[英]Mysql: Selecting values between two columns
I'm trying to select a value between 2 columns. 我正在尝试选择2列之间的值。 Here is my dataset
这是我的数据集
id from to price
1 0.00 2.00 2.50
2 2.00 3.00 3.00
3 3.00 4.00 4.50
My goal, if I have a value of 2 is to select the line with the ID 1 (between from and to). 我的目标,如果我的值为2,则选择ID为1的行(在from和to之间)。 So here is the query I'm using :
所以这是我正在使用的查询:
select * from table where 2 between from and to;
And here are the results that MySQL returns when executing this query : 以下是MySQL在执行此查询时返回的结果:
id from to price
1 0.00 2.00 2.50
2 2.00 3.00 3.00
And the result I'm looking for is the following : 我正在寻找的结果如下:
id from to price
1 0.00 2.00 2.50
I've tried using < and >, etc. But, I'm always getting two results. 我尝试过使用<和>等等。但是,我总是得到两个结果。 Any help would be much appreciated.
任何帮助将非常感激。
你可以试试这个:
SELECT * FROM `table` WHERE 2 BETWEEN `from` AND `to`
SO, you don't want the lower bound to be inclusive, right? 那么,你不希望下限包容,对吗?
SET @value = 2;
SELECT * FROM table WHERE from > @value AND @value <= to;
Query 1: 查询1:
select *
from `table`
where `from` < 2 and `to` >= 2
Output: 输出:
| ID | FROM | TO | PRICE |
--------------------------
| 1 | 0 | 2 | 3 |
Query 2: 查询2:
select *
from `table`
where `from` < 2.001 and `to` >= 2.001
Output: 输出:
| ID | FROM | TO | PRICE |
--------------------------
| 2 | 2 | 3 | 3 |
Note: With this approach, you will get no rows back for value 0
, unless you modify the query to accommodate that. 注意:使用此方法,除非您修改查询以适应该值,否则将不会为值
0
返回任何行。
You can also try this , 你也可以尝试这个,
select * from table where (from-to) = 2 // if you want the exact distance to be 2
select * from table where (from-to) >= 2 // Distance more than 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.