我有三张桌子
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
我想计算评论个人资料已获批准的帖子的评论数
我可以从帖子中选择数据,然后从评论中加入计数。但此计数应取决于配置文件是否获得批准。
我期待的结果是
评论数
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
注意:很可能有一个更优雅的解决方案!!!!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)