我有以下 items
表:
items:
id pr1 pr2 pr3
-------------------
1 11 22 tt
...
以及与项目关联的两个表:
comments:
item_id text
-------------
1 "cool"
1 "very good"
...
tags:
item_id tag
-------------
1 "life"
1 "drug"
...
现在我想得到一个包含列 item_id, pr1, pr2, count(comments), count(tags)
的表格,条件为 WHERE pr3 = zz
。获得它的最佳方法是什么?我可以通过创建额外的表来做到这一点,但我想知道是否有一种方法可以通过仅使用一个 SQL 语句来实现这一点。我正在使用 Postgres 9.3。
最佳答案
最简单的方法当然是在 select 子句中获取计数:
select
id,
pr1,
pr2,
(select count(*) from comments where item_id = items.id) as comment_count,
(select count(*) from tags where item_id = items.id) as tag_count
from items;
关于sql - 使用聚合连接三个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27600874/