有没有办法将两个更新查询合并为一个?

时间:2014-06-14 01:09:56

标签: mysql sql database join sql-update

我有多个更新查询。我想在一个声明中做到这一点。查询是

update user set name = 'Something' where id = '1';
update user set name = 'Newthing' where id = '2';

我想要像

这样的东西
update user set name = 'Something' where id = '1' && update user set name = 'Newthing' where id = '2';

2 个答案:

答案 0 :(得分:3)

当然,只需使用CASE声明:

update user 
set name = 
    case when id = '1' then 'Something' 
         when id = '2' then 'Newthing' 
    end
where id in ('1','2')

答案 1 :(得分:2)

作为sgeddes解决方案的补充:

update user u 
join ( select 1 as id,'Something' as name 
       union 
       select 2, 'Newthing') as t 
    on u.id = t.id 
        set u.name = t.name;

请注意,这只适用于mysql。其他DBMS(如Oracle,DB2,MSQL等)实现了MERGE,这是一种标准结构:

merge into user u
using (
    values (1,'Something')
         , (2,'Newthing')
) t (id, name)
    on t.id = u.id
when matched then
    update set u.name = t.name

通过添加另一个子句,您也可以插入

when not matched then
    insert (id, name) values (t.id, t.name)

此外,合并还可以删除行