我需要使用子查询的结果更新表上的多个列。一个简单的例子如下所示 –
UPDATE table1 SET (col1,col2) = ((SELECT MIN (ship_charge),MAX (ship_charge) FROM orders)) WHERE col4 = 1001;
如何在Postgresql中执行此操作?
感谢任何提示!
更新:对于我的实际使用情况,为了使样例太简单,我深表歉意。以下查询更准确 –
UPDATE table1 SET (TOTAL_MIN_RATE,TOTAL_MAX_RATE) = (SELECT AVG(o.MIN_RATE),AVG(o.MAX_RATE) FROM ORDR o INNER JOIN table2 ba ON (o.PAY_ACCT_ID = ba.ACCT_ID) INNER JOIN table3 mb ON (ba.BANK_ID = mb.BANK_ID) WHERE ba.CNTRY_ID = table1.CNTRY_ID AND o.STUS_CD IN ('01','02','03','04','05','06') AND ((o.FRO_CRNCY_ID = table1.TO_CRNCY_ID AND o.TO_CRNCY_ID = table1.FRO_CRNCY_ID) OR (o.TO_CRNCY_ID = table1.TO_CRNCY_ID AND o.FRO_CRNCY_ID = table1.FRO_CRNCY_ID)) GROUP BY ba.CNTRY_ID)
如果要避免两个子选择,则查询可以重写为:
原文链接:/postgresql/193281.htmlUPDATE table1 SET col1 = o_min,col2 = o_max FROM ( SELECT min(ship_charge) as o_min,max(ship_charge) as o_max FROM orders ) t WHERE col4 = 1001
如果ship_charge未被索引,则应该比两个子选择快。如果ship_charge被索引,这可能没有什么大的不同
编辑
从Postgres 9.5开始,这也可以写成:
UPDATE table1 SET (col1,col2) = (SELECT min(ship_charge),max(ship_charge) FROM orders) WHERE col4 = 1001