How to select records close to one in SQL?

I have one table in a database with a 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 its Id ) and 3 others that are closest to it (sorting by Money ).

So this is something like:

 SELECT * FROM test ORDER BY money LIMIT 4; 

Just with the closest (from Money ) to the selected results in a row.

+4
source share
2 answers

Sort by absolute difference:

 SELECT * FROM test ORDER BY ABS(Money - ( SELECT Money FROM test WHERE Id = 2 )) LIMIT 4; 
+4
source

SELECT * FROM test, where money> = order by money LIMIT 4; *

Ex: select * from the test, where money> = 21.00, at the price of LIMIT 4;

That would be a simpler solution.

0
source

All Articles