Find row from database depending on the value which is nearest to the given value
I want to find table row from database depending on the value which is nearest to the given value.
I have following data
Id Rate Fat
1 10 8.00
2 20 8.10
3 30 8.20
4 40 开发者_JAVA百科 8.30
5 50 8.34
6 60 8.40
7 50 8.36
suppose user want to find using the Fat
For 8.0 it should return
Id Rate Fat
1 10 8.00
For 8.06 it should return
Id Rate Fat
2 20 8.10
For 8.35 it should return 8.34 instead 8.36 (though difference is same it should give preference to lower value if difference is same)
Id Rate Fat
5 60 8.34
In SQL Server you could do this
select top 1 *
from T
order by abs(Fat - 8.35), Fat
I guess that syntax for MySQL is
select *
from T
order by abs(Fat - 8.35), Fat
limit 1
精彩评论