简体   繁体   English

postgres 根据关联连接表的计数更新值

[英]postgres update value based on count of associated join table

I have a simple scenario TableA, TableB and JoinTable that joins TableA and TableB.我有一个连接 TableA 和 TableB 的简单场景 TableA、TableB 和 JoinTable。 I want to store in TableA for each row in TableA the count of records in JoinTable that have TableAId.我想在 TableA 中为 TableA 中的每一行存储 JoinTable 中具有 TableAId 的记录数。 I can select it correctly as follows:我可以正确 select 如下:

SELECT "Id", (SELECT COUNT(*) FROM "JoinTable" WHERE "JoinTable"."TableAId" = "TableA"."Id") 
AS TOT FROM "TableA" LIMIT 100

However I'm having a hard time writing an update query.但是我很难编写更新查询。 I want to update TableA.JoinCount with this result.我想用这个结果更新 TableA.JoinCount。

You can use a correlated subquery:您可以使用相关子查询:

update tablea a
set tot = (
    select count(*)
    from jointable j
    where t.tableaid = a.id
)

This updates all rows of tablea with the count of matches from jointable ;这将使用来自jointable的匹配计数更新tablea的所有行; if there are not matches, tot is set to 0 .如果没有匹配项,则tot设置为0

I would not necessarily, however, recommend storing such derived information.但是,我不一定建议存储此类派生信息。 While it can easily be intialized with the above statement, maintaining it is tedious.虽然它可以很容易地用上面的语句初始化,但维护它是乏味的。 You will soon find yourself creating triggers for every DML operation on the join table (update, delete, insert).您很快就会发现自己为连接表上的每个 DML 操作(更新、删除、插入)创建了触发器。 Instead, you could put the information in a view:相反,您可以将信息放在视图中:

create view viewa as
select id, 
    (select count(*) from jointable j where j.tableaid = a.id) as tot
from tablea a

Side note: in general, don't use quoted identifiers in Postgres.旁注:一般来说,不要在 Postgres 中使用带引号的标识符。 This this link for more.这个这个链接更多。

You can use the group by query as the source for an UPDATE statement:您可以使用 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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