簡體   English   中英

通過聚合連接三個表

[英]Joining three tables with aggregation

我有以下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 i.id,i.pr1,i.pr2, commentcount,tagcount FROM
 items i
INNER JOIN
    (SELECT item_id,count(*) as commentcount from comments GROUP BY item_id) c
ON i.id = c.item_id
INNER JOIN
    (SELECT item_id,count(*) as tagcount from tags GROUP BY item_id) t
ON i.id = t.item_id

[評論]根據評論,這是左側的加入版本...

SELECT i.id,i.pr1,i.pr2, coalesce(commentcount,0) as commentcount,
      coalesce(tagcount,0) as tagcount FROM
     items i
    LEFT JOIN
        (SELECT item_id,count(*) as commentcount from comments GROUP BY item_id) c
    ON i.id = c.item_id
    LEFT JOIN
        (SELECT item_id,count(*) as tagcount from tags GROUP BY item_id) t
    ON i.id = t.item_id

最簡單的方法當然是在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;

嘗試這個:

SELECT i.id, i.pr1, i.pr2, A.commentCount, B.tagCount 
FROM items i
LEFT OUTER JOIN (SELECT item_id, COUNT(1) AS commentCount 
                 FROM comments 
                 GROUP BY item_id
                ) AS A ON i.id = A.item_id
LEFT OUTER JOIN (SELECT item_id, count(1) as tagCount 
                 FROM tags 
                 GROUP BY item_id
                ) AS B ON i.id = B.item_id;
select

  i.id
, i.pr1
, i.pr2
, count(c.item_id) as count_comments
, count(t.item_id) as count_tags

from items i
left outer join comments c on i.id = c.item_id
left outer join tags t on i.id = t.item_id
group by i.id, i.pr1, i.pr2

我使用了LEFT OUTER JOIN也返回零計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM