how to get nearest value from database in mysql

后端 未结 11 1096
夕颜
夕颜 2020-12-31 16:39

I am using mySQL and CodeIgniter. I have some floating point numbers in my database such as

  • 8.3456
  • 8.5555
  • 4.5556
11条回答
  •  伪装坚强ぢ
    2020-12-31 17:09

    Assuming that you have a 10% tolerance (+/-) you could try something like:

    select * from table 
    where value >= ($myvalue * .9) and value <= ($myvalue * 1.1) 
    order by abs(value - $myvalue) limit 1
    

    Slightly updated stealing from others - this should return the nearest result in the assumed tolerance range. (Also, I just noticed the where was incorrect, apologies - now it should work).

提交回复
热议问题