tags:

views:

39

answers:

3

i have users table and i have posts table i want select from users the top users that have the big amount of posts from posts table and order them by numbers of posts i can make it by array_count_values() by i cant order it now i think if i make it by one mysql query by left and join will be more better

table structure

posts

id | auther_id

i tried this

SELECT COUNT(1) cnt, u.user_id 
FROM users u 
LEFT JOIN posts p
ON p.author_id=u.user_id
GROUP BY u.user_id
ORDER BY cnt DESC
LIMIT 20

it gave me this alt text see the arrow what is this i just have 2 posts under user_id 5 what is this first row

+4  A: 

You need to aggregate the posts by user using GROUP BY u.user_id, get a COUNT value for the number of posts and ORDER BY that number, in descending order:

SELECT COUNT(1) cnt, u.user_id 
FROM users u 
LEFT JOIN posts p
ON p.author_id=u.user_id
GROUP BY u.user_id
ORDER BY cnt DESC
LIMIT 20
Andy
i think it has error its give me the count of users and posts
moustafa
You have to include the number of posts to sort by it. Don't you want the count of posts by each user?
Andy
It gives you the count of posts for each of the top 20 users and their user_id
txwikinger
its give me this row 1 cnt=15 id=2 row 2 (the thing i want) cnt=2 id=5and i just have 2 posts under 5 user id
moustafa
where are you please see my edit
moustafa
Hello I am here. The first row is 15 posts for user id 2. cnt is the number of posts, id is the user id.
Andy
+2  A: 
SELECT u.user_id, COUNT(*) as post_count
FROM   users u
INNER JOIN posts p
USING (user_id)
GROUP BY u.user_id
ORDER BY post_count
dbemerlin
A: 

i used this and its worked is it true

SELECT COUNT( 1 ) cnt, a.auther_id
FROM `posts` a
LEFT JOIN users u ON a.auther_id = u.id
GROUP BY a.auther_id
ORDER BY cnt DESC
LIMIT 20 
moustafa