user984621
user984621

Reputation: 48453

How to get all posts from each user?

I have the table users with information about every user. Then the table posts with information about articles and finally the table user_posts, which contains following columns:

user_id
post_id
...

I am trying to get the chart of users with the highest count of posts. I made this query:

SELECT u.id as uid, u.name as uname, count(up.id) as up_count FROM users as u JOIN user_posts as up ON up.user_id = u.id ORDER BY vcount DESC LIMIT 25

This query returns me only one user and the total count of all rows in the table user_posts.

What am I doing wrong? I need to get the list of 25 users sorted by the count of articles that published each user.

Thank you in advance

Upvotes: 1

Views: 721

Answers (2)

Pedigree
Pedigree

Reputation: 2594

Your query needs to have GROUP BY clause because you have used COUNT() function.

SELECT   u.id as uid, 
         u.name as uname, 
         count(up.id) as up_count 
FROM     users as u 
           LEFT JOIN user_posts as up  
              ON up.user_id = u.id 
GROUP BY u.id, u.name
ORDER BY up_count DESC LIMIT 25

You must have grouped them by ID otherwise you'll single total count result for all records. One more thing, use LEFT JOIN so even users with no post still will be visible in you result with the score of 0.

Upvotes: 3

AA.
AA.

Reputation: 4606

SELECT 
    u.id as uid, u.name as uname, count(up.id) as up_count 
FROM users as u 
    JOIN user_posts as up ON up.user_id = u.id 
GROUP BY 
    u.id, u.name
ORDER BY 
    vcount 
DESC LIMIT 25

Upvotes: 1

Related Questions