根据另一个表中的行数对mysql表进行排序

根据另一个表中的行数对mysql表进行排序,mysql,syntax,count,subquery,Mysql,Syntax,Count,Subquery,我试图根据用户在二级评论表中链接的评论数量对用户表进行排序,我认为子选择是最好的工具,但我无法获得正确的语法 用户表测试数据: id | user_id 1 | 1000 2 | 1001 3 | 1002 注释表testdata id | link_id 1 | 1002 2 | 1000 3 | 1002 4 | 1000 5 | 1002 6 | 1001 7 | 1000 8 | 1002 第一个表中的预期排序结果为: id | user_id 3 | 100

我试图根据用户在二级评论表中链接的评论数量对用户表进行排序,我认为子选择是最好的工具,但我无法获得正确的语法

用户表测试数据:

id | user_id
1  | 1000
2  | 1001
3  | 1002
注释表testdata

id | link_id
1  | 1002
2  | 1000
3  | 1002
4  | 1000
5  | 1002
6  | 1001
7  | 1000
8  | 1002
第一个表中的预期排序结果为:

id | user_id
3  | 1002
1  | 1000
2  | 1001
任何朝正确方向的推动都会非常有帮助,谢谢!=)

只要一个连接,加上count(),然后按count()排序就可以了

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


这将允许您添加来自
用户的其他列
,而无需对所有列进行
分组。

事实上,不需要使用子查询。您可以按计数使用联接和顺序:

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

同样感谢,几乎相同的解决方案=)
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
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