postgres 根据关联连接的计数更新值 table
postgres update value based on count of associated join table
我有一个简单的方案 TableA、TableB 和连接 TableA 和 TableB 的 JoinTable。我想在 TableA 中为 TableA 中的每一行存储 JoinTable 中具有 TableAId 的记录数。我可以 select 它正确如下:
SELECT "Id", (SELECT COUNT(*) FROM "JoinTable" WHERE "JoinTable"."TableAId" = "TableA"."Id")
AS TOT FROM "TableA" LIMIT 100
但是我很难编写更新查询。我想用这个结果更新 TableA.JoinCount。
您可以使用相关子查询:
update tablea a
set tot = (
select count(*)
from jointable j
where t.tableaid = a.id
)
这会用 jointable
中的匹配计数更新 tablea
的所有行;如果没有匹配项,tot
设置为 0
。
但是,我不一定会推荐存储此类派生信息。虽然可以很容易地使用上述语句对其进行初始化,但维护起来却很繁琐。您很快就会发现自己为联接 table(更新、删除、插入)上的每个 DML 操作创建了触发器。相反,您可以将信息放在视图中:
create view viewa as
select id,
(select count(*) from jointable j where j.tableaid = a.id) as tot
from tablea a
旁注:一般来说,不要在 Postgres 中使用带引号的标识符。这this link更多。
您可以使用 group by 查询作为 UPDATE 语句的来源:
update "TableA" a
set "JoinCount" = t.cnt
from (
select "TableAId" as id, count(*) as cnt
from "JoinTable"
group by "TableAId"
) t
WHERE t.id = a."Id"
我有一个简单的方案 TableA、TableB 和连接 TableA 和 TableB 的 JoinTable。我想在 TableA 中为 TableA 中的每一行存储 JoinTable 中具有 TableAId 的记录数。我可以 select 它正确如下:
SELECT "Id", (SELECT COUNT(*) FROM "JoinTable" WHERE "JoinTable"."TableAId" = "TableA"."Id")
AS TOT FROM "TableA" LIMIT 100
但是我很难编写更新查询。我想用这个结果更新 TableA.JoinCount。
您可以使用相关子查询:
update tablea a
set tot = (
select count(*)
from jointable j
where t.tableaid = a.id
)
这会用 jointable
中的匹配计数更新 tablea
的所有行;如果没有匹配项,tot
设置为 0
。
但是,我不一定会推荐存储此类派生信息。虽然可以很容易地使用上述语句对其进行初始化,但维护起来却很繁琐。您很快就会发现自己为联接 table(更新、删除、插入)上的每个 DML 操作创建了触发器。相反,您可以将信息放在视图中:
create view viewa as
select id,
(select count(*) from jointable j where j.tableaid = a.id) as tot
from tablea a
旁注:一般来说,不要在 Postgres 中使用带引号的标识符。这this link更多。
您可以使用 group by 查询作为 UPDATE 语句的来源:
update "TableA" a
set "JoinCount" = t.cnt
from (
select "TableAId" as id, count(*) as cnt
from "JoinTable"
group by "TableAId"
) t
WHERE t.id = a."Id"