sql - 使用聚合连接三个表

标签 sql postgresql left-join correlated-subquery

我有以下 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/

相关文章:

php - 左连接 - 返回许多结果

java - 来自 java jdbc 连接的架构名称 Sql 服务器

sql - 从整数转换后如何按名称排序月份?

c# - 从ASP.NET C#数据库中提取img

ruby-on-rails - ActiveRecord 数组::Base.connection.execute Ruby On Rails

mysql - 多个左连接时避免重复数据

SQL - 条件 WHERE 子句

c# - KitchenPC 和 Ironpython

php - 如何使用一个查询更新多行

MySQL:ON 或 WHERE 子句中不允许使用 LEFT JOIN、MAX