我有一个用户表和一个评论表,我想从用户中选择评论表中评论量最大的顶级用户,并按评论数量排序
只需要对论坛评论进行统计(类型可以是论坛,图片,新闻等)
表格结构
用户
id | username | password
评论
id | text | type | author_id
答案 0 :(得分:5)
SELECT
u.id,u.username,u.password ,count(c.id) as total
FROM
users u
JOIN comments c on c.author_id = u.id
GROUP BY u.id
ORDER BY total DESC;
这应该可以解决问题,试着让我们知道它是如何为你制定的
<强>更新强> 有关如何执行此操作的详细信息,您将获得this article
更新:新链接,旧链接已损坏 Databases
答案 1 :(得分:1)
SELECT users.id, users.name, COUNT(comments.id) AS cnt
FROM users
LEFT JOIN comments ON users.id = comments.author_id
WHERE type IN ('forum', 'picture', 'news', 'etc')
GROUP BY users.id
ORDER BY cnt DESC
LIMIT 10
获取评论类型为'form','picture','news'或'etc'的10位最多产的评论者。
答案 2 :(得分:1)
在PostgreSQL 8.1上测试:
select users.id, count(comments.author_id)
from users, comments
where users.id = comments.author_id
group by users.id
order by 2 desc