我有两张 table
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_quots
和 app_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
最佳答案
您不需要子选择内部的连接,只需将其设为常规的共同相关子选择即可:
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
,则相关子查询将返回 null
,并将覆盖存储在 app_supp_po_dt
在这种情况下,如果您不希望这样,则需要从 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,但很可能比具有相关子查询的解决方案快得多
关于sql - Postgres 一次更新多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32348223/