码迷,mamicode.com
首页 > 数据库 > 详细

mysql case when用户示例

时间:2015-01-18 08:14:05      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:mysq   select case   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  |
+------+------+





本文出自 “风云的博客” 博客,请务必保留此出处http://cwind.blog.51cto.com/62582/1605209

mysql case when用户示例

标签:mysq   select case   case when   

原文地址:http://cwind.blog.51cto.com/62582/1605209

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!