How to JOIN a COUNT from a table, and then effect that COUNT with another JOIN

前端 未结 3 2197
有刺的猬
有刺的猬 2021-02-13 16:52

I have three tables

Post

ID  Name
1   \'Something\'
2   \'Something else\'
3   \'One more\'

Comment

ID  PostId  Profile         


        
3条回答
  •  清歌不尽
    2021-02-13 17:41

    From the definition of the COUNT function:

    The COUNT function will only count those records in which the field in the brackets is NOT NULL.

    This means that simple outer join like this would work:

    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
    

提交回复
热议问题