Mysql
可能為 NULL 單元格的兩列的差異
我需要通過兩列的差異對錶格進行排序
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