【问题标题】:Is there any way to join two update queries into one?有没有办法将两个更新查询合并为一个?
【发布时间】:2014-08-04 15:01:03
【问题描述】:

我有多个更新查询。我想在一个声明中完成它们。查询是

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

【问题讨论】:

    标签: mysql sql database join sql-update


    【解决方案1】:

    当然,只需使用CASE 声明:

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

    【讨论】:

      【解决方案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)
      

      进一步合并也可以删除行

      【讨论】:

      • 许多其他 RDBMS 允许更新时加入(取决于版本,DB2 也取决于平台)。该合并正在做其他事情 - 如果它们不存在,它会插入行!
      • 我应该像删除删除一样提到插入,修复了。
      猜你喜欢
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 2016-08-07
      • 2021-10-23
      • 1970-01-01
      • 2018-05-29
      相关资源
      最近更新 更多