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

后端 未结 8 987
别跟我提以往
别跟我提以往 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))
    

提交回复
热议问题