MySQL的CASE WHEN语句的几个使用实例
使用case when进行字符串替换处理
9 rows in set (0.01 sec)
select name as name,
case category
when "holiday" then "seasonal"
when "profession" then "bi_annual"
when "literary" then "random" end as "pattern"
from sales;
9 rows in set (0.00 sec)
create table sales(
num mediumint not null auto_increment, name char(20), winter int, spring int,
summer int, fall int, category char(13), primary key(num)
) engine=myisam;
insert into sales value(1, 'java', 1067 , 200, 150, 267,'holiday');
insert into sales value(2, 'c',970,770,531,486,'profession');
insert into sales value(3, 'javascript',53,13,21,856,'literary');
insert into sales value(4, 'sql',782,357,168,250,'profession');
insert into sales value(5, 'oracle',589,795,367,284,'holiday');
insert into sales value(6, 'mysql',953,582,336,489,'literary');
insert into sales value(7, 'cplus',752,657,259,478,'literary');
insert into sales value(8, 'python',67,23,83,543,'holiday');
insert into sales value(9, 'php',673,48,625,52,'profession');
简单语句
select case when 10*2=30 then '30 correct'
when 10*2=40 then '40 correct'
else 'should be 10*2=20'
end as `result`;
多重表达式
when 20 then '20 correct'
when 30 then '30 correct'
when 40 then '40 correct'
else 'no results'
end as `result`;
在select查询中使用case when
id smallint not null auto_increment primary key,
name varchar(60) not null,
numdisks tinyint not null default 1,
ratingid varchar(4) not null,
statid char(3) not null
) engine=innodb;
insert into dvds (name, numdisks, ratingid, statid)
values ('christmas', 1, 'nr', 's1'), ('doc', 1, 'g', 's2'), ('africa', 1, 'pg', 's1'), ('falcon', 1, 'nr', 's2'),
('amadeus', 1, 'pg', 's2'), ('show', 2, 'nr', 's2'), ('view', 1, 'nr', 's1'), ('mash', 2, 'r', 's2');
select name, ratingid as rating,
case ratingid
when 'r' then 'under 17 requires an adult.'
when 'x' then 'no one 17 and under.'
when 'nr' then 'use discretion when renting.'
else 'ok to rent to minors.'
end as policy
from dvds
order by name;
8 rows in set (0.01 sec)
推荐阅读
-
在MySQL中使用JOIN语句进行连接操作的详细教程
-
MYSQL的REPLACE和ON DUPLICATE KEY UPDATE语句介绍解决问题实例
-
在python3环境下的Django中使用MySQL数据库的实例
-
MySQL定时备份之使用Linux下的crontab定时备份实例
-
MySQL Like语句的使用方法
-
详解MySQL插入和查询数据的相关命令及语句使用
-
浅析SQL语句行列转换的两种方法 case...when与pivot函数的应用
-
MySQL中UPDATE语句使用的实例教程
-
MySQL存储过程中使用WHILE循环语句的方法
-
MySQL中join语句的基本使用教程及其字段对性能的影响