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
例子:
-> 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:
-> WHEN 2 THEN 'two' ELSE 'more' END;
-> 'one'
如果case后面的表达式和when中的值相等,则返回相对应then后的值,否则返回else的值。
例2:
-> WHEN 'a' THEN 1 WHEN 'b' THEN 2 END;
-> NULL
这个例子和上面的类似,只不过没有else值,返回null
例3:
-> 'true'
如果case后面的值为真,返回then值,否则返回else值。
案例:统计各班级中的及格与不及格人数
+----+-------+-------+-------+
| 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语句:
+-------+--------------+-----------------+-----------+
| class | 及格人数 | 不及格人数 | 总人数 |
+-------+--------------+-----------------+-----------+
| 1 | 2 | 3 | 5 |
| 2 | 6 | 0 | 6 |
| 3 | 1 | 2 | 3 |
+-------+--------------+-----------------+-----------+
3 rows in set (0.00 sec)
以上通过实例介绍了mysql内置函数case的用法,希望对大家有所帮助。
您可能感兴趣的文章:
mysql内置函数case用法介绍
mysql case实例:带条件检测的case语句
mysql的call用法 嵌套函数调用的例子
mysql case实例:在存储过程中使用CASE WHEN语句
mysql case实例:在存储过程中使用CASE WHEN条件
mysql case实例:分组检测条件值
mysql case实例:CASE WHEN with ELSE的用法
mysql怎么去除字段中换行符与回车符
mysql substr()函数简介
mysql实例 repeat语句的用法