2010-04-10 47 views
9

我有三个表如何JOIN从一个表的计数,然后实现与另一种COUNT JOIN

ID Name 
1 'Something' 
2 'Something else' 
3 'One more' 

评论

ID PostId ProfileID Comment 
1 1  1   'Hi my name is' 
2 2  2   'I like cakes' 
3 3  3   'I hate cakes' 

档案

ID Approved 
1 1   
2 0   
3 1   

我想数t他评论的评论的个人资料被批准

我可以从帖子中选择数据,然后从评论加入计数罚款。但是这个数字应该取决于配置文件是否被批准。

我期待的结果是

CommentCount

PostId Count 
1  1 
2  0 
3  1 
+0

是'Profile'表1-1与'Comment'一个? – 2010-04-10 10:36:57

+1

不,一个配置文件可以做出许多评论。 – 2010-04-10 10:44:36

回答

11

你可以使用一个嵌套的选择是这样的:

SELECT Post.Id, temp.Count 
FROM Post 
LEFT JOIN 
(SELECT Post.Id, COUNT(Comment.ID) AS Count 
FROM Post 
LEFT JOIN Comment ON Comment.PostId = Post.ID 
LEFT JOIN Profile ON Profile.ID = Comment.ProfileID 
WHERE Profile.Approved = 1 
GROUP BY Post.Id) 
temp ON temp.Id = Post.ID 

这将使你空在那里没有任何职位,而不是没有记录:

1 1 
2 null 
3 1 

只是为了改善这一点,你可以使用一个if来摆脱空值

SELECT Post.Id, if(temp.Count >= 1,temp.Count,0) as newCount 
FROM Post 
LEFT JOIN 
(SELECT Post.Id, COUNT(Comment.ID) AS Count 
FROM Post 
LEFT JOIN Comment ON Comment.PostId = Post.ID 
LEFT JOIN Profile ON Profile.ID = Comment.ProfileID 
WHERE Profile.Approved = 1 
GROUP BY Post.Id) temp ON temp.Id = Post.ID 

哪给你你最初想要的:

1 1 
2 0 
3 1 

注:最有可能是一个更优雅的解决方案,虽然!!!!

+0

好的工作。谢谢! – 2010-04-11 10:48:57

1
SELECT Post.Id, COUNT(Comment.ID) AS Count 
FROM Post 
LEFT JOIN Comment ON Comment.PostId = Post.ID 
LEFT JOIN Profile ON Profile.ID = Comment.ProfileID 
WHERE Profile.Approved = 1 
GROUP BY Post.Id 

也许你没有粘贴的例子的目的,但你可能会评估到反规范化的Profile表与Comment一起,移动Approved列。

+0

这是一个好主意!虽然意味着需要更多的编码,以确保当配置文件被批准和暂停时,表格保持最新状态。 另外,如何让表名在代码中以代码的形式显示? – 2010-04-10 10:43:55

+0

使用你的〜键,'卢克' – jonny 2010-04-10 10:50:44

+0

这给了我正确的计数,但只有'帖子'有'评论'。即使他们没有任何评论,我也需要返回所有'Posts'。我在开始时并没有明确表示道歉。 – 2010-04-10 11:23:57

4

从COUNT函数的定义:

COUNT函数将只计算那些 记录,其中在 括号中的字段不为空。

这意味着,简单的外连接像这样的工作:

SELECT Post.ID, COUNT(Comment.ID) 
    FROM Post LEFT JOIN Comment ON (Post.ID = Comment.PostId) 
      LEFT JOIN Profile ON (Profile.ID = Comment.ProfileID AND 
            Profile.Approved = 1) 
GROUP BY Post.ID 
+0

这也不起作用,它只返回两行。即使“COUNT”为空,我也需要返回所有行。 – 2010-04-11 10:47:48

+0

对不起,当然它不 - 看看我如何移动Profile.Approved条件来修复它... – topchef 2010-04-11 17:55:36

+2

+1这应该是答案。 – 2012-03-05 23:56:53