在 Postgres 中使用条件 where 子句更新多行?
Updating multiple rows with a conditional where clause in Postgres?
我试图在单个查询中更新多行,因为我有很多行要同时更新。在我的查询中,有一个仅适用于某些行的 where 子句。
例如,我有以下查询:
update mytable as m set
column_a = c.column_a,
column_b = c.column_b
from (values
(1, 12, 6, TRUE),
(2, 1, 45, FALSE),
(3, 56, 3, TRUE)
) as c(id, column_a, column_b, additional_condition)
where c.id = m.id
and CASE c.additional_condition when TRUE m.status != ALL(array['active', 'inactive']) end;
where
子句 (m.status != ALL(array['active', 'inactive'])
) 中的最后一行应仅应用于 c.additional_condition
值中具有 TRUE
的行。否则,不应应用该条件。
是否可以在 Postgres 中实现这一点?
我觉得你想要的逻辑是:
where c.id = m.id and
( (not c.additional_condition) and orm.status = 'active' )
您可以对多个值使用 in
或数组:
where c.id = m.id and
( (not c.additional_condition) and orm.status not in ( 'active', 'inacctive') )
我没有看到使用数组的特定值,除非您将值作为数组传递。
我想这就是你想要的:
and CASE
when c.additional_condition THEN m.status != ALL(array['active', 'inactive'])
else TRUE
end
我试图在单个查询中更新多行,因为我有很多行要同时更新。在我的查询中,有一个仅适用于某些行的 where 子句。
例如,我有以下查询:
update mytable as m set
column_a = c.column_a,
column_b = c.column_b
from (values
(1, 12, 6, TRUE),
(2, 1, 45, FALSE),
(3, 56, 3, TRUE)
) as c(id, column_a, column_b, additional_condition)
where c.id = m.id
and CASE c.additional_condition when TRUE m.status != ALL(array['active', 'inactive']) end;
where
子句 (m.status != ALL(array['active', 'inactive'])
) 中的最后一行应仅应用于 c.additional_condition
值中具有 TRUE
的行。否则,不应应用该条件。
是否可以在 Postgres 中实现这一点?
我觉得你想要的逻辑是:
where c.id = m.id and
( (not c.additional_condition) and orm.status = 'active' )
您可以对多个值使用 in
或数组:
where c.id = m.id and
( (not c.additional_condition) and orm.status not in ( 'active', 'inacctive') )
我没有看到使用数组的特定值,除非您将值作为数组传递。
我想这就是你想要的:
and CASE
when c.additional_condition THEN m.status != ALL(array['active', 'inactive'])
else TRUE
end