我有三张 table
邮政
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 中加入一个计数。但是这个计数应该取决于配置文件是否被批准。
我期待的结果是
评论数
PostId Count
1 1
2 0
3 1
最佳答案
您可以使用这样的嵌套选择:
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
注意:虽然很可能有一个更优雅的解决方案!!!!
关于sql - 如何从表中加入 COUNT,然后用另一个 JOIN 影响该 COUNT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2613005/