I don't know quite how to phrase this so please help me with the title as well. :)

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.

I'm using Postgresql 9 right now, but I guess this would be a generic SQL question?

EDIT:

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

Sql相关问答推荐

如何重用表值用户定义函数调用的结果?

SQL Google Sheets:UNIQUE/DISTINCT和编码查询函数

Select /过滤postgr中的树 struct

用于匹配红旗和绿旗的SQL查询

NULL-生成的列中连接的字符串的输入

每年独特口味的冰淇淋数量

使用DatePart函数对日期时间值进行分组

Redshift PL/pgSQL循环中的参数化列名

SQL按日期分组字段和如果日期匹配则求和

SQL Athena/prest判断值是否在嵌套的json数组中

明细表中没有记录如何更新主表的值为0

基于另一个(SAS、SQL)中的值更新列

获取主表条目,其中最新的辅助条目是 6 个月前

根据标识符将两行合并为一行

删除对 JSON 数据的未解析引用的 SQL71502 警告

SQL:考虑合并分支计算分支的增长百分比

SQL Server - 复杂场景 - 比较状态并填充值到后续行

Snowflake中的动态SQL优化

如何获取每个组中最近的n条记录并将它们聚合成数组

删除具有相同 ID 的重复记录 - Postgresql