Sort mysql table based on the number of rows in another table

I am trying to sort a user table based on how many comments they linked to them in the secondary comment table. I figured sub-selection would be the best tool, but I can't get the syntax correctly.

Test data table for users:

id | user_id
1  | 1000
2  | 1001
3  | 1002

Testdata table comment table p>

id | link_id
1  | 1002
2  | 1000
3  | 1002
4  | 1000
5  | 1002
6  | 1001
7  | 1000
8  | 1002

The expected sorted result in the first table:

id | user_id
3  | 1002
1  | 1000
2  | 1001

Any push in the right direction would be extremely helpful, thanks! =)

+3
source share
4 answers

In fact, there is no need to use a subquery. You can use JOIN and ORDER BY 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
+3

, (), ()

select c.id, user_id, count(*) from user u, comments c where u.id = c.id group by id, user_id

-ACE

+2
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
+1
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 will allow you to add other columns from userswithout having group byall of them.

0
source

Source: https://habr.com/ru/post/1732090/


All Articles