mysql case when用戶示例

看到一些朋友在使用bind-dlz時寫的mysql語句只知其一;不知其二,索性本身動手寫幾個示例實驗一下,加深印象,廢話很少說,直解上料:mysql

1)原始記錄
sql

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
express

 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示例2ide

#當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   |
+------+---------------------------------------------+
ci

3.3示例2input

#任意列均可覺得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  |
+------+------+





it

相關文章
相關標籤/搜索