如何使此SQL更新语句更有效?

时间:2012-07-17 16:10:47

标签: sql postgresql aggregate-functions

我正在尝试将计数,求和和平均值从一个表添加到另一个表,但我最终查询每个值的相同数据。我正在使用PostgreSQL。我正在向专家们讨论如何使这个更新语句更有效率。这是:

update "table1" set 
"col1" = (SELECT COUNT(*) FROM "table2" WHERE "table2Id" = "table1"."table1Id"), 
"col2" = (SELECT AVG("someCol") FROM "table2" WHERE "table2Id" = "table1"."table1Id"),
"col3" = (SELECT SUM("someCol") FROM "table2" WHERE "table2Id" = "table1"."table1Id");

我应该能够像这样运行一个子查询并访问更新的返回值,对吗?

SELECT COUNT(*), AVG("someCol"), SUM("someCol") FROM "table2" WHERE "table2Id" = "table1"."table1Id";

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:5)

尝试子查询:

UPDATE table1 
SET col1 = YourCount, col2 = YourAverage, col3 = YourSum
FROM table1 t1
INNER JOIN (
    SELECT table2Id, COUNT(*) AS YourCount, AVG(someCol1) YourAverage, 
        SUM(someCol2) YourSum
    FROM table2
    GROUP BY table2Id
) t2 ON t1.table1Id = t2.table2Id

答案 1 :(得分:1)

我相信最近(9.0+)版本的Postgresql,可以使用CTE进行更清晰的查询。

WITH calculations AS 
   (SELECT table2ID, COUNT(*) AS n, SUM(someCol) AS s, AVG(someCol) AS a
    FROM table2
    GROUP BY table2ID)
UPDATE table1
SET col1=n, col2=s, col3=a
FROM calculations WHERE calculations.table2ID=table1.table1ID;