使用子查询更新postgres中的表格行

使用postgres 8.4,我的目标是更新现有的表格:

CREATE TABLE public.dummy ( address_id SERIAL, addr1 character(40), addr2 character(40), city character(25), state character(2), zip character(5), customer boolean, supplier boolean, partner boolean ) WITH ( OIDS=FALSE ); 

最初我使用insert语句testing了我的查询:

 insert into address customer,supplier,partner SELECT case when cust.addr1 is not null then TRUE else FALSE end customer, case when suppl.addr1 is not null then TRUE else FALSE end supplier, case when partn.addr1 is not null then TRUE else FALSE end partner from ( SELECT * from address) pa left outer join cust_original cust on (pa.addr1=cust.addr1 and pa.addr2=cust.addr2 and pa.city=cust.city and pa.state=cust.state and substring(cust.zip,1,5) = pa.zip ) left outer join supp_original suppl on (pa.addr1=suppl.addr1 and pa.addr2=suppl.addr2 and pa.city=suppl.city and pa.state=suppl.state and pa.zip = substring(suppl.zip,1,5)) left outer join partner_original partn on (pa.addr1=partn.addr1 and pa.addr2=partn.addr2 and pa.city=partn.city and pa.state=partn.state and pa.zip = substring(partn.zip,1,5) ) where pa.address_id = address_id 

正在新手我无法转换为更新语句,即更新select语句返回值的现有行。 任何帮助,高度赞赏。

Postgres允许:

 UPDATE dummy SET customer=subquery.customer, address=subquery.address, partn=subquery.partn FROM (SELECT address_id, customer, address, partn FROM /* big hairy SQL */ ...) AS subquery WHERE dummy.address_id=subquery.address_id; 

这种语法不是标准的SQL,但对于这种types的查询比标准的SQL更方便。 我相信甲骨文(至less)接受类似的东西。

你在UPDATE FROM语法之后。

 UPDATE table T1 SET column1 = t2.column1 FROM table t2 INNER JOIN table t3 USING (column2) WHERE t1.column2 = t2.column2; 

参考

  • 这里的代码示例: UPDATE FROM子句中的GROUP BY
  • 和这里
  • forms语法规范

如果使用连接没有性能提升,那么为了便于阅读,我更喜欢公用表expression式(CTE):

 WITH subquery AS ( SELECT address_id, customer, address, partn FROM /* big hairy SQL */ ... ) UPDATE dummy SET customer=subquery.customer, address=subquery.address, partn=subquery.partn FROM subquery WHERE dummy.address_id=subquery.address_id; 

恕我直言,有点现代。