【问题标题】:Update multiple rows in one query在一个查询中更新多行
【发布时间】:2016-01-15 10:27:44
【问题描述】:

我的当前表:

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

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

【问题讨论】:

  • 新价值观背后的逻辑是什么?
  • 其实就是一个名为ordering的列。他们想颠倒这种顺序。

标签: sql postgresql postgresql-9.3


【解决方案1】:

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

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

【讨论】:

  • 我的错,应该是“员工”
猜你喜欢
  • 2019-07-17
  • 2014-06-26
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
  • 2022-12-17
  • 2022-01-20
  • 2017-03-13
  • 1970-01-01
相关资源
最近更新 更多