Postgres 一次更新多行

Postgres update multiple row in one action

我有两张桌子

app_detail_quot_s
-----------+--------------+
part_id    +unit_price    +
-----------+--------------+
1          +    100.000   +
2          +    200.000   +
3          +    300.000   +


app_supp_po_dt
-----------+--------------+
part_id    +unit_price    +
-----------+--------------+
1          +    null      +
2          +    null      +
8          +    null      +

执行查询更新后的结果是

app_supp_po_dt
-----------+--------------+
part_id    +unit_price    +
-----------+--------------+
1          +    100.000   +
2          +    200.000   +
8          +    null      +

app_detail_quotsapp_supp_po_detail 之间的 part_id 在使用 PostgreSQL 的一次操作中相等时,如何更新所有 unit_price

我正在尝试这个代码:

update app_supp_po_dt set
    unit_price =
 ( 
    select unit_price from app_detail_quot_s a left join app_supp_po_dt b on    a.part_id= b.part_id
 ) 

但是我得到错误:

more than one row returned by a subquery used as an expression

你不需要子select里面的连接,只需要让它成为一个常规的关联子select:

update app_supp_po_dt 
 set unit_price = (select unit_price 
                   from app_detail_quot_s a 
                   where a.part_id = app_supp_po_dt.part_id);

上面假设part_id在两个表中都是唯一的。

如果在 app_detail_quot_s 中找不到 part_id,则相关子查询将 return null 并将覆盖存储在 [=17= 中的任何值] 在这种情况下,如果您不希望这样,则需要从 app_supp_po_dt 中排除具有单价但未出现在 app_detail_quot_s

中的行
update app_supp_po_dt 
 set unit_price = ( select unit_price from app_detail_quot_s a where a.part_id = app_supp_po_dt.part_id)
where unit_price is null
  and exists (select 1 
              from app_detail_quot_s a2 
              where a2.part_id = app_supp_po_dt.part_id);

另一个(非标准)选项是在 update 语句中使用连接,这使语句更具可读性:

update app_supp_po_dt 
  set unit_price = a.unit_price
from app_detail_quot_s a
where a.part_id = app_supp_po_dt.part_id;

这是非标准的 SQL,不适用于其他 DBMS,但很可能比具有相关子查询的解决方案快得多