一条SQL语句执行批量修改

UPDATE mytable SET 
myfield = CASE id 
    WHEN 1 THEN 'value'
    WHEN 2 THEN 'value'
    WHEN 3 THEN 'value'
END
WHERE id IN (1,2,3)

例如

UPDATE categories SET 
display_order = CASE id 
    WHEN 1 THEN 3 
    WHEN 2 THEN 4 
    WHEN 3 THEN 5 
END, 
title = CASE id 
    WHEN 1 THEN 'New Title 1'
    WHEN 2 THEN 'New Title 2'
    WHEN 3 THEN 'New Title 3'
END
WHERE id IN (1,2,3)

这句sql的意思是,更新display_order 字段,如果id=1 则display_order 的值为3,如果id=2 则 display_order 的值为4,如果id=3 则 display_order 的值为5。
即是将条件语句写在了一起。
这里的where部分不影响代码的执行,但是会提高sql执行的效率。确保sql语句仅执行需要修改的行数,这里只有3条数据进行更新,而where子句确保只有3行数据执行。

如果是多条件:

UPDATE test_user SET
`password` = CASE
    WHEN id=1 AND name='rose' THEN '2fffffffff'
    WHEN id=2 AND name='jack' THEN '2fddddddd'
ELSE `password` END

或者多字段多条件

UPDATE `table` SET 
total = CASE
    WHEN goodsid=50 AND id=21 AND storeid=3 THEN 86
    WHEN goodsid=49 AND id=22 AND storeid=3 THEN 85
ELSE total END ,
openid = CASE
    WHEN goodsid=50 AND id=21 AND storeid=3 THEN 'aaa'
    WHEN goodsid=49 AND id=22 AND storeid=3 THEN 'bbb'
ELSE openid END

例如:

UPDATE `ims_sz_yi_store` SET 
`district_id` = CASE 
     WHEN id=5 AND uniacid=2 THEN 3 
     WHEN id=8 AND uniacid=3 THEN 7
ELSE `district_id` END 

通过新增临时表的方法

create temporary table tmp(id int(4) primary key,dr varchar(50));
insert into tmp values  (0,'gone'), (1,'xx'),...(m,'yy');
update test_tbl, tmp set test_tbl.dr=tmp.dr where test_tbl.id=tmp.id;
Last modification:September 2nd, 2020 at 10:35 am
如果觉得我的文章对你有用,请随意赞赏