I have a table with columns,ID, A and B, where I introduce some values
INSERT INTO test VALUES(1, 1, 6);
INSERT INTO test VALUES(2, 5, 8);
INSERT INTO test VALUES(3, 3, 4);
INSERT INTO test VALUES(4, 4, 5);
Now I´m looking for a query to tell me if a range of numbers that I pass to the query are between those values or not. So If I pass 2 and 3 (could be N numbers) I expect to see row 1 and 3.
So far the only thing that I achieve is using the IN to know If my number is in that column, but not if is higher or lower.
SELECT * FROM table WHERE A IN ('2', '3')
I think I would need create a function. Somebody can point me in the right direction here please?
To find all rows where the range contains the specified numbers:
SELECT *
FROM test
WHERE (2 BETWEEN A AND B)
OR (3 BETWEEN A AND B)
/* OR (4 BETWEEN A AND B) */
/* OR (5 BETWEEN A AND B) */
+------+------+------+
| ID | A | B |
+------+------+------+
| 1 | 1 | 6 |
| 3 | 3 | 4 |
+------+------+------+
An alternate solution is to JOIN
your table with the list of numbers:
SELECT DISTINCT test.*
FROM test
INNER JOIN (
SELECT 2 AS num UNION ALL
SELECT 3 /* UNION ALL
SELECT 4 UNION ALL
SELECT 5 */
) AS num_list ON num_list.num BETWEEN test.A AND test.B
Use BETWEEN
SELECT * FROM table WHERE A BETWEEN 1 AND 3
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.