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

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

    You could use a nested select like this:

    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
    

    Which would give you null where there are no posts, rather than no record:

    1  1
    2  null
    3  1
    

    Just to improve on that, you could use an if to get rid of the nulls

    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
    

    Which gives you what you originally wanted:

    1  1
    2  0
    3  1
    

    Note: There is most probably a more elegant solution though!!!!

提交回复
热议问题