我有三张桌子
发布
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
我想计算评论的个人资料获得批准的帖子的评论
我可以从Post中选择数据,然后从Comment fine中加入一个计数。但是这个计数应该取决于配置文件是否被批准。
我期待的结果是
CommentCount
PostId Count
1 1
2 0
3 1
答案 0 :(得分:12)
你可以使用这样的嵌套选择:
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
如果没有帖子而不是没有记录,哪个会给你null:
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
注意:虽然!!!!
可能是更优雅的解决方案答案 1 :(得分:5)
从COUNT函数的定义:
COUNT功能只会计算 那些领域的记录 括号不是NULL。
这意味着像这样的简单外连接可以起作用:
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
答案 2 :(得分: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
表一起取消规范化列中。