How to find least non-null column in one particular row in SQL?

后端 未结 8 982
别跟我提以往
别跟我提以往 2020-12-29 07:36

I am trying to find the lowest number in two columns of a row in the same table, with the caveat that one of the columns may be null in a particular row. If one of the colum

8条回答
  •  长发绾君心
    2020-12-29 08:26

    One simple (yet not beautiful) solution is the following.

    If you're looking for the smallest non-null value, you can use IFNULL with the second parameter beingthe 'INT limit'

    ORDER BY LEAST(
        IFNULL(properties.sale_value, 2147483647),
        IFNULL(properties.rental_value, 2147483647),
        IFNULL(properties.daily_rental_value, 2147483647)
    ) ASC
    

    And if you're looking for the biggest non-null value, you can use IFNULL with the second parameter being 1, ( or the first negative value below your limit, if you don't know it, use the negative int limit )

    ORDER BY GREATEST(
        IFNULL(properties.sale_value, 1),
        IFNULL(properties.rental_value, 1),
        IFNULL(properties.daily_rental_value, 1)
    ) ASC
    

提交回复
热议问题