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