在Postgres SELECT语句中选择另一个表中的行数 [英] Select count of rows in another table in a Postgres SELECT statement
问题描述
我不知道该如何措辞,因此请同时为我提供标题。 :)
I don't know quite how to phrase this so please help me with the title as well. :)
我有两个表。我们称它们为 A
和 B
。 B
表具有一个 a_id
外键,该外键指向 A.id
。现在,我想编写一个 SELECT
语句,该语句将提取所有 A
记录,并增加一个包含<对于结果集中的每一行,每 A
行有code> B 条记录。
I have two tables. Let's call them A
and B
. The B
table has a a_id
foreign key that points at A.id
. Now I would like to write a SELECT
statement that fetches all A
records, with an additional column containing the count of B
records per A
row for each row in the result set.
我现在正在使用Postgresql 9,但是我想这将是一个通用的SQL问题?
I'm using Postgresql 9 right now, but I guess this would be a generic SQL question?
编辑:
最后,我使用了触发器缓存解决方案,其中 A.b_count
每次通过 B $都会通过函数进行更新。 c $ c>更改。
In the end I went for trigger-cache solution, where A.b_count
is updated via a function each time B
changes.
推荐答案
SELECT A.*, (SELECT COUNT(*) FROM B WHERE B.a_id = A.id) AS TOT FROM A
这篇关于在Postgres SELECT语句中选择另一个表中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!