Mysql: Selecting values between two columns

2019-02-16 08:37发布

I'm trying to select a value between 2 columns. 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). 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 :

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.

4条回答
Deceive 欺骗
2楼-- · 2019-02-16 08:59

SO, you don't want the lower bound to be inclusive, right?

SET @value = 2;
SELECT * FROM table WHERE from > @value AND @value <= to;
查看更多
不美不萌又怎样
3楼-- · 2019-02-16 09:09

Query 1:

select * 
from `table` 
where `from` < 2 and `to` >= 2

SQL Fiddle Example

Output:

| ID | FROM | TO | PRICE |
--------------------------
|  1 |    0 |  2 |     3 |

Query 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.

查看更多
走好不送
4楼-- · 2019-02-16 09:10

You could try this:

SELECT * FROM `table` WHERE 2 BETWEEN `from` AND `to`
查看更多
闹够了就滚
5楼-- · 2019-02-16 09:13

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 
查看更多
登录 后发表回答