问题描述
您可以像这样使用嵌套选择:
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来消除null
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
注意:不过,最有可能是更优雅的解决方案!!!!
解决方法
我有三表
Post
ID Name
1 'Something'
2 'Something else'
3 'One more'
Comment
ID PostId ProfileID Comment
1 1 1 'Hi my name is'
2 2 2 'I like cakes'
3 3 3 'I hate cakes'
Profile
ID Approved
1 1
2 0
3 1
我想计算发表评论的个人资料被批准的帖子的评论
我可以从Post中选择数据,然后从Comment fine中加入一个计数。但是此计数应取决于配置文件是否被批准。
我期望的结果是
评论数
PostId Count
1 1
2 0
3 1