在一个查询中更新多行

时间:2016-01-15 10:27:44

标签: sql postgresql postgresql-9.3

我目前的表格:

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 个答案:

答案 0 :(得分: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';