我有一个用户表和一个评论表,我想从用户中选择评论表中包含大量评论的顶级用户,并按评论数量排序
表格结构
用户
id | username | password
评论
id | text | author_username
答案 0 :(得分:3)
使用以下MySQL语句列出评论最多的用户。 CommentCount
会告诉您特定用户发表的评论数量。
SELECT
users.username,
COUNT(comments.id) AS CommentCount
FROM
users
INNER JOIN comments ON users.id = comments.author_userid
GROUP BY
users.username
ORDER BY
COUNT(comments.id) DESC
请注意,您必须先将author_userid
更改为author_username
!
答案 1 :(得分:0)
我的SQL有点生疏,但是这样的东西会给你你想要的东西(虽然我提到过,用户ID应该是comments
表中唯一的用户标识符。)
Select count(id), author_username from comments group by author_username
答案 2 :(得分:0)
select u.username,count(c.comments) as total
from users as u
left join comments as c
on u.username = c.author_username
group by u.username
order by total desc
我会改变连接字段,因为dutchie432建议。添加限制子句以获得所需的记录数。