1

我正在尝试将一个表中的计数、总和和平均值添加到另一个表中,但我最终为每个值查询相同的数据。我正在使用 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";

任何帮助深表感谢。

4

2 回答 2

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
于 2012-07-17T16:16:03.157 回答
1

我相信在 Postgresql 的最新(9.0+)版本中,可以使用 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;
于 2012-07-17T18:57:06.013 回答