Mysql的case-when-end语句

Mysql的case-when-end语句

1.什么情况下需要使用case-when-end语句?
  • 当需要依据条件的取值而决定某值的选择时,可以使用case-when-end语句
2.给出一个示例
  • 2.1 新建一个数据库,名为mydatabase,注意字符串为utf8模式
create table country(
country varchar(255),
population varchar(255)
)
  • 2.2 往表中插入数据
insert into mydatabase.country VALUES
("英国","200"),
("法国","300"),
("日本","250"),
("德国","200"),
("墨西哥","50"),
("印度","250"),
("中国","600"),
  • 2.3 对表进行一些修改
rename table country to myworld;#重改表名
desc mydatabase.myworld;#查看表结构
select * from mydatabase.myworld;#查看表完整数据
  • 2.4.使用如下语法
case 
when …… then ……
else ……
end ……
select 
case 
when population="600" then "Earth"#when 中的变量与select的项没有必然的关系
else "Other"
end country , population#这里的select项是case中的country和population
from mydatabase.myworld;

执行结果如下:

+---------+------------+
| country | population |
+---------+------------+
| Earth   | 600        |
| Other   | 100        |
| Other   | 200        |
| Other   | 300        |
| Other   | 250        |
| Other   | 200        |
| Other   | 50         |
| Other   | 250        |
+---------+------------+
8 rows in set (0.00 sec)

注:上面的SQL语句和下面的这个SQL语句没有差别,

select 
population,#这里的select项是population 和case语句中的country
case 
when population="600" then "Earth"#when 中的变量与select的项没有必然的关系
else "Other"
end country#注意这里没有逗号
from mydatabase.myworld;

执行结果如下:

+------------+---------+
| population | country |
+------------+---------+
| 600        | Earth   |
| 100        | Other   |
| 200        | Other   |
| 300        | Other   |
| 250        | Other   |
| 200        | Other   |
| 50         | Other   |
| 250        | Other   |
+------------+---------+
8 rows in set (0.00 sec)
select 
case 
when country="中国" then "Earth"
when country="美国" then "Mercury"
when country="日本" then "Moon"
else "Other"
end country , population
from mydatabase.myworld;

执行结果如下:

+---------+------------+
| country | population |
+---------+------------+
| Earth   | 600        |
| Mercury | 100        |
| Other   | 200        |
| Other   | 300        |
| Moon    | 250        |
| Other   | 200        |
| Other   | 50         |
| Other   | 250        |
+---------+------------+
8 rows in set (0.00 sec)
  • 2.使用如下语法:
case ……
when …… then ……
else ……
end 
select 
case country
when "中国" then "Earth"
when "美国" then "Mercury"
when "日本" then "Moon"
else "Other"
end as newTitle , population
from mydatabase.myworld;

注:

  • 1.一般end 之后就可以结束了,但是这里使用了end as ,将其替换为一个新的标题显示出来。
  • 2.case- when- end 并不是一个什么特别的语句,只是在select的时候,如果有其它的条件,可以去除或者添加某些项。或者为某些项赋值
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

说文科技

看书人不妨赏个酒钱?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值