Ilya Gazman
Ilya Gazman

Reputation: 32226

Mysql select closest match from table

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

Upvotes: 1

Views: 876

Answers (2)

Zane Bien
Zane Bien

Reputation: 23125

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

Upvotes: 3

Andreas
Andreas

Reputation: 1781

SELECT * 
 FROM table
 WHERE ID <= 8
 ORDER BY ID DESC
 LIMIT 1

Upvotes: 0

Related Questions