Select closest numerical value with MySQL query

后端 未结 3 1778
温柔的废话
温柔的废话 2020-12-03 11:39

This is probably easier than I am making it, but basically what I need to do is select the row that has the closest number in a column as a specified value. For example:

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 12:07

    How would you handle tie breakers? Because this will only take the first:

      SELECT t.col
        FROM TABLE t
    ORDER BY ABS(t.col - @val)
       LIMIT 1
    

    Index safe alternative:

      SELECT xt.col
        FROM (SELECT t.col,
                     ABS(t.col - @val) 'diff'
                FROM TABLE t) xt
    ORDER BY xt.diff
       LIMIT 1
    

提交回复
热议问题