case

description

Syntax

  1. CASE expression
  2. WHEN condition1 THEN result1
  3. [WHEN condition2 THEN result2]
  4. ...
  5. [WHEN conditionN THEN resultN]
  6. [ELSE result]
  7. END

OR

  1. CASE WHEN condition1 THEN result1
  2. [WHEN condition2 THEN result2]
  3. ...
  4. [WHEN conditionN THEN resultN]
  5. [ELSE result]
  6. END

将表达式和多个可能的值进行比较,当匹配时返回相应的结果

example

  1. mysql> select user_id, case user_id when 1 then 'user_id = 1' when 2 then 'user_id = 2' else 'user_id not exist' end test_case from test;
  2. +---------+-------------+
  3. | user_id | test_case |
  4. +---------+-------------+
  5. | 1 | user_id = 1 |
  6. | 2 | user_id = 2 |
  7. +---------+-------------+
  8. mysql> select user_id, case when user_id = 1 then 'user_id = 1' when user_id = 2 then 'user_id = 2' else 'user_id not exist' end test_case from test;
  9. +---------+-------------+
  10. | user_id | test_case |
  11. +---------+-------------+
  12. | 1 | user_id = 1 |
  13. | 2 | user_id = 2 |
  14. +---------+-------------+

keywords

CASE