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

后端 未结 8 945
别跟我提以往
别跟我提以往 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:25

    Unfortunately (for your case) behaviour of LEAST was changed in MySQL 5.0.13 (http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_least) - it used to return NULL only if all arguments are NULL.

    This change was even reported as a bug: http://bugs.mysql.com/bug.php?id=15610 But the fix was only to MySQL documentation, explaining new behaviour and compatibility break.

    Your solution was one of the recommended workarounds. Another can be using IF operator:

    SELECT IF(Col1 IS NULL OR Col2 IS NULL, COALESCE(Col1, Col2), LEAST(Col1,Col2))
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题