使用联接查找更新单个列

时间:2015-03-18 11:20:44

标签: sql postgresql

我有一个表adjustments,其中包含adjustable_id | adjustable_type | order_id

order_id是要填充值的目标列,此值应来自另一个具有line_items列的表order_idadjustable_id (int) and _type (varchar)引用该表。

table: adjustments
id  | adjustable_id | adjustable_type | order_id
------------------------------------------------
100 | 1             | line_item       | NULL
101 | 2             | line_item       | NULL

table: line_items
id | order_id | other | columns
--------------------------------
1  | 10       | bla   | bla
2  | 20       | bla   | bla

在上面的情况中,我想我需要一个连接查询来更新adjustments.order_id第一行的值为10,第二行更新为20,依此类推其他行使用Postgres 9.3+

如果查找失败,我需要删除无效的adjustments行,因为它们没有相应的line_items。

2 个答案:

答案 0 :(得分:1)

有两种方法可以做到这一点。第一个使用共同相关的子查询:

update adjustments a
  set order_id = (select lorder_id 
                  from line_items l
                  where l.id = a.adjustable_id)
where a.adjustable_type = 'line_item';

这是标准的ANSI SQL,因为标准SQL没有为UPDATE语句定义连接条件。

第二种方法是使用连接,这是SQL标准的Postgres扩展(其他DBMS也支持但具有不同的语义和语法)。

update adjustments a
  set order_id = l.order_id 
from line_items l
where l.id = a.adjustable_id
  and a.adjustable_type = 'line_item';

联接可能是更快的。请注意,如果line_items和adjust之间的连接始终只返回line_items表中的一行,则两个版本(尤其是第一个版本)将有效。如果不是这样,他们就会失败。

Arockia查询的原因是"吃掉你的内存"是他/她的查询在table1和table1之间创建一个交叉连接,然后连接到table2。

Postgres手册contains a warning about that

  

请注意,目标表必须出现在from_list中,除非您打算进行自我加入

答案 1 :(得分:-1)

从table1更新一组A.name = B.name一个连接table2 B on A.id = B.id

相关问题