How to select records close to one in SQL?
I have a single table in database, with 开发者_StackOverflowa structure like:
Id | Name | Money
--------------------------
1 | Joe | 34.50
2 | Jane | 12.55
3 | Kate | 55.21
4 | George | 9.54
5 | Hilary | 45.21
6 | Jacob | 32.00
7 | Ginny | 21.00
Now I want to select one specified record (knowing it's Id
) and 3 others, closest to it (sorting by Money
).
So it's something like:
SELECT * FROM test ORDER BY money LIMIT 4;
Just with closest (by Money
) to selected row's money results.
Sort by the absolute difference:
SELECT * FROM test
ORDER BY ABS(Money - (
SELECT Money FROM test WHERE Id = 2
))
LIMIT 4;
SELECT * FROM test where money>= order by money LIMIT 4;*
Ex: Select * from test where money >=21.00 order by money LIMIT 4;
This would be a simpler solution.
精彩评论