MySQL Find the total amount of posts per user

前端 未结 2 1837
失恋的感觉
失恋的感觉 2021-02-10 02:07

I have a Database with the following two tables, USERS, POSTS I am looking for a way to get the count of how many posts a user has.

Users            P         


        
相关标签:
2条回答
  • 2021-02-10 03:05
    select users.*, count(posts.user_id)
    
    from users, posts
    where users.user_id = posts.user_id
    group by posts.user_id
    

    But the best way is too add a field to the users table and keep the amount of posts made by each users, and updated it whenever a post is created or deleted. Otherwise, you'll slow down your DB when it grows bigger.

    0 讨论(0)
  • 2021-02-10 03:07

    Figured it out. Smacks self in head

    SELECT users.*, count( posts.user_id ) 
    FROM posts LEFT JOIN users ON users.id=posts.user_id 
    GROUP BY posts.user_id
    
    0 讨论(0)
提交回复
热议问题