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

前端 未结 3 2207
有刺的猬
有刺的猬 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:52

    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
    

    Probably you didn't paste it for the sake of the example, but you might evaluate to de-normalize the Profile table together with the Comment one, by moving the Approved column in it.

提交回复
热议问题