代码之家  ›  专栏  ›  技术社区  ›  Michael Bui

在一个查询中更新多行

  •  0
  • Michael Bui  · 技术社区  · 9 年前

    我的当前表格:

    id | count | group_id
    1    1      employee   
    2    2      employee   
    3    3      employee   
    4    4      employee   
    

    我想要什么:

    id | count | group_id
    1    4      employee   
    2    3      employee   
    3    2      employee   
    4    1      employee 
    

    我所尝试的

     UPDATE table SET count = 4 WHERE count = 1 AND group_id='employee';
     UPDATE table SET count = 3 WHERE count = 2 AND group_id='employee';
     UPDATE table SET count = 2 WHERE count = 3 AND group_id='employee';
     UPDATE table SET count = 1 WHERE count = 4 AND group_id='employee';
    

    由于明显的原因,这不起作用,因为它逐行执行每个查询,所以我的结果是错误的。我想我正在寻找一种用一个查询更新多个表的方法?

    1 回复  |  直到 9 年前
        1
  •  1
  •   jarlh    9 年前

    这个具体案例可以这样解决:

    UPDATE table SET count = 5 - count
    WHERE count between 1 and 4 AND group_id= 'employee';
    

    更一般的解决方案是使用 CASE 表达式:

    UPDATE table SET count = case count when 4 then 1
                                        when 3 then 2
                                        when 2 then 3
                                        when 1 then 4
                             end
    WHERE count between 1 and 4 AND group_id = 'employee';