Mysql select closest match from table
Question
I got a table that looks like that:
ID|DATA
1 | ok
4 | ok2
5 | kk
6 | same ok
7 | k
9 | yeah
I want to find the closest match(round down) to my id. When I pass
id = 8
I want to select the raw 7 | K
How do I do that in mySql
Solution
You can use this solution:
SELECT id, data
FROM tbl
WHERE id <= 8
ORDER BY id DESC
LIMIT 1
Alternatively, here's another way you can do it without having to use ORDER BY
/ LIMIT
:
SELECT b.id, b.data
FROM (SELECT MAX(id) AS id FROM tbl WHERE id <= 8) a
JOIN tbl b ON a.id = b.id
OTHER TIPS
SELECT *
FROM table
WHERE ID <= 8
ORDER BY ID DESC
LIMIT 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow