Mysql

可能為 NULL 單元格的兩列的差異

  • August 19, 2018

我需要通過兩列的差異對錶格進行排序

SELECT (first - second) AS dif
   FROM table1
ORDER BY dif DESC

但兩列都可以NULL。在這種情況下,它返回錯誤:

BIGINT UNSIGNED value is out of range

此錯誤的解決方案是使用IFNULL(col,0),但問題是dif如果NULL任何列是我需要NULL

您可以在進行計算之前測試列是否為空。

SELECT if(isnull(first) or isnull(second),null,(ifnull(first,0) - ifnull(secon,0))) AS dif
   FROM table1
ORDER BY dif DESC

有很多方法可以做到這一點,但我覺得這是可讀的:

SELECT CASE WHEN first IS NULL OR second IS NULL THEN NULL
      ELSE first - second END AS dif
   FROM table1
ORDER BY 1 DESC

引用自:https://dba.stackexchange.com/questions/213798