Sort mysql table based on number of rows in another table
I'm trying to sort a user table开发者_JAVA技巧 based on how many comments they have linked to them in a secondary comment-table, I figured a sub-select will be the best tool but I can't get the syntax correct.
Users table testdata:
id | user_id
1 | 1000
2 | 1001
3 | 1002
Comment table testdata
id | link_id
1 | 1002
2 | 1000
3 | 1002
4 | 1000
5 | 1002
6 | 1001
7 | 1000
8 | 1002
Expected sorted result in the first table would be:
id | user_id
3 | 1002
1 | 1000
2 | 1001
Any push in the right direction would be extremly helpful, thanks! =)
In fact, there is no need to use a sub-query. You can use a JOIN and ORDER BY the count:
SELECT
users.user_id, COUNT(comments.id) as total_messages
FROM
users
INNER JOIN
comments ON comments.link_id = users.id
GROUP BY
user_id
ORDER BY
COUNT(comments.id) DESC
just a join, with a count(), and then an order by the count() should do it
select c.id, user_id, count(*) from user u, comments c where u.id = c.id group by id, user_id
-ace
SELECT
u.id,
u.user_id
COUNT(u.id) link_count
FROM
Users u,
Comment c
WHERE
c.link_id = u.user_id
ORDER BY
link_count
GROUP BY
u.id,
u.user_id
SELECT u.id, u.user_id
FROM users u
JOIN ( SELECT link_id, COUNT(*) cnt FROM comment GROUP BY link_id ) c
ON ( c.link_id = u.user_id )
ORDER BY c.cnt DESC
This would allow you to add other columns from users
without having to group by
them all.
精彩评论