如何从表中加入COUNT,然后使用另一个JOIN实现该COUNT

Jak*_*e N 11 sql join count

我有三张桌子

岗位

ID  Name
1   'Something'
2   'Something else'
3   'One more'
Run Code Online (Sandbox Code Playgroud)

评论

ID  PostId  ProfileID  Comment
1   1       1          'Hi my name is' 
2   2       2          'I like cakes'
3   3       3          'I hate cakes'
Run Code Online (Sandbox Code Playgroud)

轮廓

ID  Approved
1   1          
2   0          
3   1          
Run Code Online (Sandbox Code Playgroud)

我想计算批评评论的个人资料的评论

我可以从Post中选择数据,然后从Comment fine中加入一个计数.但是这个计数应该取决于配置文件是否被批准.

我期待的结果是

CommentCount

PostId  Count
1       1
2       0
3       1
Run Code Online (Sandbox Code Playgroud)

the*_*ite 14

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

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
Run Code Online (Sandbox Code Playgroud)

如果没有帖子,而不是没有记录,哪个会给你null:

1  1
2  null
3  1
Run Code Online (Sandbox Code Playgroud)

只是为了改进,你可以使用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
Run Code Online (Sandbox Code Playgroud)

这给了你最初想要的东西:

1  1
2  0
3  1
Run Code Online (Sandbox Code Playgroud)

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


top*_*hef 5

从COUNT函数的定义:

COUNT函数仅计算括号中的字段为NOT 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
Run Code Online (Sandbox Code Playgroud)