前言:
函數是MySQL控制流函數之一,它根據一個條件返回一個值。IF函數有時被稱為IF ELSE或IF THEN ELSE函數。
IF函數語法如下:
IF(expr,if_true_expr,if_false_expr)
IF函數通常與SUM()函數組合,
SELECT SUM(IF(status = 'Shipped', 1, 0)) AS Shipped, SUM(IF(status = 'Cancelled', 1, 0)) AS Cancelled FROM orders;
IF函數與COUNT()函數組合,因為COUNT函數不計算空值,所以如果狀態不在選定狀態,IF函數將返回NULL,否則將返回1。
SELECT COUNT(IF(status = 'Cancelled', 1, NULL)) Cancelled, COUNT(IF(status = 'Disputed', 1, NULL)) Disputed, COUNT(IF(status = 'In Process', 1, NULL)) 'In Process', COUNT(IF(status = 'On Hold', 1, NULL)) 'On Hold', COUNT(IF(status = 'Resolved', 1, NULL)) 'Resolved', COUNT(IF(status = 'Shipped', 1, NULL)) 'Shipped' FROM orders;