mysqlcasewhenthen使⽤,实现批量更新
建表:
create table hank (id int,name varchar(20));
插⼊数据:
insert into hank values(1,'A');
insert into hank values(2,'B');
insert into hank values(3,'C');
通过case when then更新数据:
update hank set name = case id
when 1 then 'D'
when 2 then 'E'
when 3 then 'F'
end
where id in(1,2,3);
sql的意思是,更新name字段,如果id=1 则name的值为D,如果id=2 则 name 的值为E,如果id=3 则 name 的值为F。
即是将条件语句写在了⼀起。
这⾥的where部分不影响代码的执⾏,但是会提⾼sql执⾏的效率。确保sql语句仅执⾏需要修改的⾏数,这⾥只有3条数据进⾏更新,⽽where⼦句确保只有3⾏数据执⾏
表的创建
CREATE TABLE `lee` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` char(20) DEFAULT NULL,
`birthday` datetime DEFAULT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8
数据插⼊:
insert into lee(name,birthday) values ('sam','1990-01-01');
insert into lee(name,birthday) values ('lee','1980-01-01');
insert into lee(name,birthday) values ('john','1985-01-01');
第⼀种⽤法:
SELECT name,
CASE WHEN birthday < '1981' THEN 'old'
WHEN birthday > '1988' THEN 'yong'
ELSE 'ok' END YORN
FROM lee
第⼆种⽤法:
SELECT NAME, CASE name
WHEN 'sam' THEN 'yong'
WHEN 'lee' THEN 'handsome'
ELSE 'good' END as oldname
FROM lee
批量更新sql语句第三种:当然了,case when 语句还可以复合
select name, birthday,
case
when birthday > '1983' then 'yong'
when name='lee' then 'handsome'
else 'just so so' end
from lee;
在这⾥⽤sql语句进⾏⽇期⽐较的话,需要对年加引号,要不然可能结果和预期的结果不同,
当然也可以⽤year函数来实现
select name,
case when year(birthday) > 1988 then 'yong'
when year(birthday) < 1980 then 'old'
else 'ok' END
from lee;
==========================================================
create table penalties
(
paymentno INTEGER not NULL,
payment_date DATE not null,
amount DECIMAL(7,2) not null,
primary key(paymentno)
)
insert into penalties values(1,'2008-01-01',3.45);
insert into penalties values(2,'2009-01-01',50.45);
insert into penalties values(3,'2008-07-01',80.45);
第⼀题:对登记分为三类,第⼀类low,包括⼤于0⼩于等于40的,第⼆类moderate⼤于40到80之间的,第三类high包含所有⼤于80的
select payment_date, amount,
case
when amount >= 0 AND amount < 40 then 'low'
when amount >=40 AND amount < 80 then 'moderate'
when amount >=80 then 'high'
else 'null' END
FROM penalties
第⼆题:统计出属于low的编号
select * from
( select paymentno, amount,
case
when amount >= 0 AND amount < 40 then 'low'
when amount >=40 AND amount < 80 then 'moderate' when amount >=80 then 'high'
else 'incorrect' end lvl
from penalties) as p
where p.lvl = 'low'