MySQL中 case函数认识和用法

**case 主要两种格式:**

手机表
id name count type
1 iphone 5 苹果
2 mi 2 小米
3 huawei 4 华为
4 oppo 1 OPPO


1.简单case函数:
case name 
    when 'xiaomi' then '国产'
    when 'huawei' then '国产'
    when 'iphone' then '进口'
else '其他' end
2.搜索case函数:
case  
    when name = 'xiaomi' then '国产'
    when name = 'huawei' then '国产'
    when name = 'iphone' then '进口'
else '其他' end
二者都可实现功能,不过推荐使用case搜索函数.
注意:case只返回第一个符合条件的值,剩下的case 部分会被忽略.
case函数的功能很强大,介绍一个实用的:

我要分组统计进口手机国产手机的总量count:

sql语句:

select 
case name 
when 'iphone' then '进口'
else '国产' end as '手机来源',
sum(count) as '出货量(万部)'
from phone group by
case name 
when 'iphone' then '进口'
else '国产' end ;

执行输出如下:

手机来源 出货量(万部)
国产 7
进口 5

在Case函数中,可以使用BETWEEN,LIKE,IS NULL,IN,EXISTS等等。比如说使用IN,EXISTS,可以进行子查询,从而 实现更多的功能。 还可以使用合计函数max()等,在此不去举例了.

猜你喜欢

转载自blog.csdn.net/harry5508/article/details/84819491