CASE 子句
說明
CASE
子句使用規則,根據指定條件傳回特定結果,類似其他程式語言中的 if/else 陳述式。
語法
CASE [ expression ] { WHEN boolean_expression THEN then_expression } [ ... ]
[ ELSE else_expression ]
END
參數
-
boolean_expression
指定任何評估為結果類型
boolean
的表達式。可以使用邏輯運算子(AND
、OR
)將兩個或多個表達式結合在一起。 -
then_expression
根據
boolean_expression
條件指定 then 表達式;then_expression
和else_expression
都應為相同類型或可強制轉換為共用類型。 -
else_expression
指定預設表達式;
then_expression
和else_expression
都應為相同類型或可強制轉換為共用類型。
範例
CREATE TABLE person (id INT, name STRING, age INT);
INSERT INTO person VALUES
(100, 'John', 30),
(200, 'Mary', NULL),
(300, 'Mike', 80),
(400, 'Dan', 50);
SELECT id, CASE WHEN id > 200 THEN 'bigger' ELSE 'small' END FROM person;
+------+--------------------------------------------------+
| id | CASE WHEN (id > 200) THEN bigger ELSE small END |
+------+--------------------------------------------------+
| 100 | small |
| 200 | small |
| 300 | bigger |
| 400 | bigger |
+------+--------------------------------------------------+
SELECT id, CASE id WHEN 100 then 'bigger' WHEN id > 300 THEN '300' ELSE 'small' END FROM person;
+------+-----------------------------------------------------------------------------------------------+
| id | CASE WHEN (id = 100) THEN bigger WHEN (id = CAST((id > 300) AS INT)) THEN 300 ELSE small END |
+------+-----------------------------------------------------------------------------------------------+
| 100 | bigger |
| 200 | small |
| 300 | small |
| 400 | small |
+------+-----------------------------------------------------------------------------------------------+
SELECT * FROM person
WHERE
CASE 1 = 1
WHEN 100 THEN 'big'
WHEN 200 THEN 'bigger'
WHEN 300 THEN 'biggest'
ELSE 'small'
END = 'small';
+------+-------+-------+
| id | name | age |
+------+-------+-------+
| 100 | John | 30 |
| 200 | Mary | NULL |
| 300 | Mike | 80 |
| 400 | Dan | 50 |
+------+-------+-------+