mysql内置函数case用法介绍

发布时间:2020-12-05编辑:脚本学堂
本文介绍下,mysql内置函数case的用法,通过实例学习下case内置函数的用法,有需要的朋友参考下。

本节内容:
mysqlneizhihanshu/ target=_blank class=infotextkey>mysql内置函数case使用介绍

mysql对case函数的解释:
 

复制代码 代码示例:
mysql> ? case
Many help items for your request exist.
To make a more specific request, please type 'help <item>',
where <item> is one of the following
topics:
   CASE OPERATOR
   CASE STATEMENT
mysql> ? case operator
Name: 'CASE OPERATOR'
Description:
Syntax:
CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN
result ...] [ELSE result] END
CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]
[ELSE result] END
The first version returns the result where value=compare_value. The
second version returns the result for the first condition that is true.
If there was no matching result value, the result after ELSE is
returned, or NULL if there is no ELSE part.
 

URL: http://dev.mysql.com/doc/refman/5.1/en/control-flow-functions.html

例子:
 

复制代码 代码示例:
mysql> SELECT CASE 1 WHEN 1 THEN 'one'
    ->     WHEN 2 THEN 'two' ELSE 'more' END;
        -> 'one'
mysql> SELECT CASE WHEN 1>0 THEN 'true' ELSE 'false' END;
        -> 'true'
mysql> SELECT CASE BINARY 'B'
    ->     WHEN 'a' THEN 1 WHEN 'b' THEN 2 END;
        -> NULL

例1:
 

复制代码 代码示例:
mysql> SELECT CASE 1 WHEN 1 THEN 'one'
    ->     WHEN 2 THEN 'two' ELSE 'more' END;
        -> 'one'
 

如果case后面的表达式和when中的值相等,则返回相对应then后的值,否则返回else的值。

例2:
 

复制代码 代码示例:
mysql> SELECT CASE BINARY 'B'
    ->     WHEN 'a' THEN 1 WHEN 'b' THEN 2 END;
        -> NULL
 

这个例子和上面的类似,只不过没有else值,返回null

例3:
 

复制代码 代码示例:
mysql> SELECT CASE WHEN 1>0 THEN 'true' ELSE 'false' END;
        -> 'true'
 

如果case后面的值为真,返回then值,否则返回else值。

案例:统计各班级中的及格与不及格人数
 

复制代码 代码示例:
mysql> select * from student;
+----+-------+-------+-------+
| id | class | name  | score |
+----+-------+-------+-------+
|  1 |     1 | name1 |    50 |
|  2 |     1 | name2 |    30 |
|  3 |     2 | name1 |    60 |
|  4 |     1 | name2 |    30 |
|  5 |     2 | name1 |    60 |
|  6 |     1 | name2 |    70 |
|  7 |     2 | name1 |    60 |
|  8 |     1 | name2 |    70 |
|  9 |     2 | name1 |    60 |
| 10 |     3 | name2 |    70 |
| 11 |     2 | name1 |    60 |
| 12 |     3 | name2 |    20 |
| 13 |     2 | name1 |    60 |
| 14 |     3 | name2 |    20 |
+----+-------+-------+-------+
14 rows in set (0.00 sec)

sql语句
 

复制代码 代码示例:
mysql> select class,count(case when score>=60 then 1 end) as '及格人数',count(case when score<60 then 1 end) as '不及格人数',count(*) as '总人数' from student group by class;
+-------+--------------+-----------------+-----------+
| class | 及格人数     | 不及格人数      | 总人数    |
+-------+--------------+-----------------+-----------+
|     1 |            2 |               3 |         5 |
|     2 |            6 |               0 |         6 |
|     3 |            1 |               2 |         3 |
+-------+--------------+-----------------+-----------+
3 rows in set (0.00 sec)

以上通过实例介绍了mysql内置函数case的用法,希望对大家有所帮助。