Is there a postgres CLOSEST operator?

前端 未结 4 523
再見小時候
再見小時候 2020-12-01 23:55

I\'m looking for something that, given a table like:

| id | number |
|  1 |     .7 |
|  2 |   1.25 |
|  3 |   1.01 |
|  4 |    3.0 |

the qu

4条回答
  •  不知归路
    2020-12-02 00:18

    The 2nd answer is correct, but I encountered error on "UNION ALL":

    DBD::Pg::st execute failed: ERROR: syntax error at or near "UNION"

    I fixed it with this code:

    SELECT * FROM
      (
        (SELECT * FROM table WHERE num >= ? ORDER BY num LIMIT 1)
            UNION ALL
        (SELECT * FROM table WHERE num < ?  ORDER BY num DESC LIMIT 1)
      ) as foo
    ORDER BY abs(?-num) LIMIT 1;
    

    the trick is to remove the AS from the inner tables and use it only on the UNION.

提交回复
热议问题