mysql case when用户示例

看到一些朋友在使用bind-dlz时写的mysql语句一知半解,索性自己动手写几个示例实验一下,加深印象,废话不多说,直解上料:

1)原始记录

mysql> select id,name from test;
+------+------+
| id   | name |
+------+------+
|    1 | lili |
|   10 | yaya |
|   30 | cici |
+------+------+

2)语法
CASE input_expression
    WHEN when_expression THEN result_expression
        [ ...n ]
    [
        ELSE else_result_expression
    END


CASE   
WHEN Boolean_expression THEN result_expression
        [ ...n ]
    [
        ELSE else_result_expression
    END

3)示例
--------------  示例 -----------------------
3.1示例1

 mysql>  select name,  
    ->      case   
    ->             when id<'9' then 'yong'  
    ->             when id>'15' then 'old'  
    ->             else 'ok' END YORN  
    ->     from test;
+------+------+
| name | YORN |
+------+------+
| lili | yong |
| yaya | ok   |
| cici | old  |
+------+------+
3.2示例2

#当end后面没有用于该列的简写时
mysql> select name,  
    ->        case   
    ->                when id<'9' then 'yong'
    ->                when id>'15' then 'old'
    ->                else 'ok' END   
    ->        from test;

+------+----------------------------------------------------------------+
| name | case   
               when id<'9' then 'yong'
               when id>'15' then 'old'
               else 'ok' END |
+------+----------------------------------------------------------------+
| lili | yong  |
| yaya | ok    |
| cici | old   |
+------+---------------------------------------------+

3.3示例2

#任意列都可以为when的值,如id
mysql> select name,  
       case   
               when id<'9' then 'yong'
               when id>'15' then id
               else 'ok' END yarn  
       from test;

+------+------+
| name | yarn |
+------+------+
| lili | yong |
| yaya | 10   |
| cici | old  |
+------+------+





你可能感兴趣的:(case,case,select,mysq,when)