简体   繁体   中英

checking multiple values in between two columns mysql

I am trying for a MySQL query to check multiple values between two columns values. For example, for one value here is my query which works

SELECT column3
FROM table
WHERE (12 between minvaluecol AND maxvaluecol) AND
      id = 123;

I would like to check multiple values like (12,13,14,67,68) and should return the values that are in between minvaluecol and maxvaluecol columns. In this case, only 12,13,14 are in between minvaluecol and maxvaluecol columns whereas 67,68 are not.

my table looks like this,

id   | minvaluecol | maxvaluecol
---- | ----------- | ------------
121  | 23          |  35
123  | 10          |  20
125  | 40          |  50   

output for id 123 should look like,

12  | true
13  | true
14  | true
67  | false
68  | false

Please help me with this query in MySQL. Thank you.

Update

Completely revamped the answer based on updated question.

As you need all the values as different rows, you need to SELECT all of them with UNION and LEFT JOIN it with the original table, eg:

SELECT a.val, IF(a.val BETWEEN tv.minvaluecol AND maxvaluecol, 'true', 'false') AS result
FROM (
SELECT 12 AS val
UNION 
SELECT 13 AS val
UNION 
SELECT 14 AS val
UNION 
SELECT 67 AS val
UNION 
SELECT 68 AS val) a
JOIN test_values tv
WHERE tv.id = 123;

Here's the SQL Fiddle .

The easiest way to get your result is to Insert those values into a table and then join like this:

SELECT value, 
   CASE WHEN value between minvaluecol AND maxvaluecol THEN 'true ELSE 'false' END
FROM table 
CROSS JOIN table_with_values
WHERE id = 123
ORDER BY value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM