MySQL CASE语句是一种流控制功能,它使我们能够在查询中建立条件,例如SELECT或WHERE子句。我们有两种CASE语句的语法
CASE val WHEN compare_val1 THEN result1 WHEN compare_val2 THEN result2 . . . Else result END
在此,在第一种语法中,如果val等于compare_val1,则CASE语句返回result1。如果val等于compare_val2,则CASE语句返回result2,依此类推。
如果val与任何compare_val不匹配,则CASE语句返回 ELSE子句中指定的结果。
mysql> Select CASE 100 -> WHEN 100 THEN 'It is matched' -> WHEN 200 THEN 'It is not matched' -> ELSE 'No use of this Number' -> END as 'Matching the Number'; +---------------------+ | Matching the Number | +---------------------+ | It is matched | +---------------------+ 1 row in set (0.06 sec)
CASE WHEN condition_1 THEN result1 WHEN condition_2 THEN result2 . . . Else result END
在这里,使用 第二种语法,CASE语句返回result1,result2等。如果条件为真。如果所有条件都为假,则CASE语句返回 ELSE子句中指定的结果。
mysql> Select CASE -> WHEN (100 = 100) THEN 'It is Matched' -> WHEN (200 = 100) Then 'It is Not Matched' -> Else 'No use of Number' -> END as 'Matching the Number'; +---------------------+ | Matching the Number | +---------------------+ | It is Matched | +---------------------+ 1 row in set (0.00 sec)