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的时候,如果有其它的条件,可以去除或者添加某些项。或者为某些项赋值