我必须在PostgreSQL 9.1中更新许多行中的许多列。我目前正在使用许多不同的UPDATE
查询,每个查询在不同的行上工作(基于主键):
UPDATE mytable SET column_a = 12, column_b = 6 WHERE id = 1;
UPDATE mytable SET column_a = 1, column_b = 45 WHERE id = 2;
UPDATE mytable SET column_a = 56, column_b = 3 WHERE id = 3;
我必须做几千个这样的查询。
无论如何,我可以在PostgreSQL的一个查询中“批量更新”大量行吗?如果您使用的是INSERT
,则可以一次插入多行:(INSERT INTO mytable (column_a, column_b) VALUES ( (12, 6), (1, 45) );
),是否有类似UPDATE
的内容?
类似的东西:
UPDATE mytable SET (id, column_a, column_b) FROM VALUES ( (1, 12, 6), (2, 1, 45), (3, 56, 3), … )
...
重点是每个'VALUE'只会更新一行(基于WHERE id =
)。每行都有相同的,固定数量的列需要更新,但每行的每列都有不同的值,因此UPDATE mytable SET column_a = 12, column_b = 6 WHERE id IN (1, 2, 3);
将不起作用。
答案 0 :(得分:18)
是的,您可以(通常在SQL中首选)一次更新多行。有几种方法可以做到这一点,但我认为最可读和优雅的是使用具有id' s和值的派生表:
update mytable as m set
column_a = c.column_a,
column_b = c.column_b
from (values
(1, 12, 6),
(2, 1, 45),
(3, 56, 3)
) as c(id, column_a, column_b)
where c.id = m.id
不太可读,但更明显的解决方案是使用case
:
update mytable set
column_a = case id when 1 then 12 when 2 then 1 when 3 then 56 end,
column_b = case id when 1 then 6 when 2 then 45 when 3 then 3 end
where id in (1, 2, 3)
答案 1 :(得分:7)
如果这适用于您的情况,您可以使用它。
create table test(id int, a int, b int);
insert into test(id, a, b)
values
(1, 1, 1),
(2, 1, 1),
(3, 1, 1),
(4, 1, 1),
(5, 1, 1),
(6, 1, 1),
(7, 1, 1);
update test as d
set a = s.a, b = s.b
from
(
values
(1, 2, 2),
(2, 2, 2)
) as s(id, a, b)
where d.id = s.id
<强> SQL FIDDLE DEMO 强>