Postgres - 使用限制更新同一查询中的多行

Jen*_*ijn 3 postgresql postgresql-9.6

我正在尝试使用以下语句更新表中的多行:

update test as t set
    column_a = c.column_a
from (values
    ('123', 1),
    ('345', 2)  
) as c(column_b, column_a) 
where c.column_b = t.column_b;
Run Code Online (Sandbox Code Playgroud)

但是,在我的数据库中 column_b 中的值不是唯一的(例如,多行可以有“123”)。我还有一个带有 DATE 类型的 column_c。对于更新语句中的每一行,我只希望上述更新发生在 column_c 中具有最新日期的行上,例如通过按日期对数据进行排序并使用 LIMIT 1。

因此,我试图将此查询与此处提供的答案结合起来。但是,我很难做到这一点。

ype*_*eᵀᴹ 5

您可以使用派生表或 cte 为每个查找一行(最新的)column_b

with upd as
( select distinct on (t.column_b) 
      t.pk, c.column_a              -- pk : the primary key column(s)
  from test as t
    join
      (values
         ('123', 1),
         ('345', 2)  
      ) as c (column_b, column_a) 
    on c.column_b = t.column_b
  order by t.column_b, t.date desc
) 
update test as t 
set column_a = upd.column_a
from upd
where upd.pk = t.pk ;
Run Code Online (Sandbox Code Playgroud)