我有四个表格,结构如下:
panelists
(panelist_id
,first_name
,last_name
等。)projects
(project_id
,title
,created_date
等。)panelists_on_projects
(pp_id
,panelist_id
,project_id
等。)comments
(comment_id
,panelist_id
,project_id
等。)想象一下,我在同一个项目中有四个小组成员(“x”),但只有3个小组成员留下了评论。我试图找出一个查询来计算每个小组成员的评论,并为附加到项目x的小组成员返回零,但是谁没有留下评论。
我尝试使用以下内容:
SELECT first_name, last_name, COUNT(comment_id)
from panelists
INNER JOIN comments USING (panelist_id)
WHERE project = x
但我只得到实际发表评论的3名小组成员的结果。有什么建议吗?
答案 0 :(得分:2)
outer join
是关键部分,我也认为您在评论加入中忘记了该项目。按特定列计数时,不会计算空值。
select
pj.project_id,
p.panelist_id,
p.firstname,
p.lastname,
totalcomments = count(c.comment_id)
from
project pj
inner join panelists_on_projects pop on pop.project_id = pj.project_id
inner join panelist p on p.panelist_id = pop.panelist_id
left outer join comments c on
c.panelist_id = p.panelist_id
and c.project_id = pj.project_id
where
pj.title = 'X'
group by
pj.project_id,
p.panelist_id,
p.firstname,
p.lastname
答案 1 :(得分:0)
这是我的实施。虽然如果你知道project_id,你可以直接进入panelists_on_projects表。
select
pan.first_name
, pan.last_name
, count(com.comment_id)
from
projects proj
inner join panelists_on_project pop
on proj.panelist_id = pop.panelist_id
inner join panelist pan
on pop.panelist_id = pan.panelist_id
left outer join comments com
on pan.panelist_id = com.panelist_id
and com.project_id = proj.project_id
where
proj.title = 'x'
group by
pan.first_name
, pan.last_name
如果没有评论联接的第二个条件and com.project_id = proj.project_id
,这将是项目'x'上的小组成员的所有项目的评论总数的计数
答案 2 :(得分:0)
SELECT P.first_name, P.last_name, COUNT(C.comment_id)
FROM panelists as P
LEFT JOIN panelists_on_projects AS PP ON PP.panelist_id = P.panelist_id
LEFT JOIN projects AS PR PN PP.project_id = PR.project_id
LEFT OUTER JOIN comments As C ON C.panelist_id = P.panelist_id AND C.project_id = PR.project_id
WHERE PR.title = "x"