how to get nearest value from database in mysql

后端 未结 11 1162
夕颜
夕颜 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:22

    (
    select   *
    from     table
    where    value >= $myvalue
    order by value asc
    limit 1
    )
    union
    (
    select   *
    from     table
    where    value < $myvalue
    order by value desc
    limit 1
    )
    order by abs(value - $myvalue)
    limit 1
    

    This may look counter-intuitive but the speed will be greater than the other queries shown so far.

    This is due to the fact that a greater than and less than query is quicker.

    Then doing an ABS on two values is nothing.

    This will give you the quickest return in a single query I can think of.

    Doing an ABS on a whole table will be slow as it will scan the whole table.

提交回复
热议问题