简体   繁体   中英

How can I make this SQL update statement more efficient?

I am trying to add count, sum, and average values from one table to another, but I end up querying the same data for each value. I'm using PostgreSQL. I'm turning this over to the experts to learn how to make this update statement more efficient. Here it is:

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");

I should be able to run a subquery like this once and access the returned values for the update, correct?

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

Any help is much appreciated.

Try a subquery:

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

I believe in recent (9.0+) versions of Postgresql, it is possible to use a CTE for a cleaner looking query.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM