当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL的CASE WHEN语句的几个使用实例

MySQL的CASE WHEN语句的几个使用实例

2017年12月12日  | 移动技术网IT编程  | 我要评论

使用case when进行字符串替换处理

复制代码 代码如下:
mysql> select * from sales;

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`;

多重表达式
复制代码 代码如下:
select case 10*2
   when 20 then '20 correct'
   when 30 then '30 correct'
   when 40 then '40 correct'
   else 'no results'
end as `result`;

在select查询中使用case when
复制代码 代码如下:
create table dvds (
   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)

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网