首先,使用SQL数据库需要在关联表之间定义JOIN语句来获取引用的关系数据。
由于您需要获得大多数帖子的TOP 10 用户,因此当用户具有相同的帖子数并应被视为相同排名时,使用LIMIT 10 的传统方法会出现问题。 E.g: 4人发5帖,3人发6帖..
为了解决上面相同的帖子数问题,我们将选择RANK query,这会将帖子数相同的人视为相同的排名。
SELECT users.fullname, posting_rank_stats.total_posts, posting_rank_stats.posting_rank
FROM users
INNER JOIN
(
SELECT author_id, total_posts, RANK() OVER (ORDER BY post_author_count.total_posts DESC) AS posting_rank
FROM
(
SELECT COUNT(*) AS total_posts, author_id
FROM posts
GROUP BY author_id
) post_author_count
) posting_rank_stats
ON users.id = posting_rank_stats.author_id
-- we only want to search for top 10
WHERE posting_rank_stats.posting_rank <= 10;
碎成小块:
1.获取每个用户的帖子数
首先,我们获取每个用户的帖子数,这需要COUNT 函数和GROUP BY author_id
SELECT COUNT(*) AS total_posts, author_id
FROM posts
GROUP BY author_id
2。计算帖子数排名
使用RANK() 函数计算帖子的排名。排名位置由total_posts的最高数量决定
SELECT author_id, total_posts, RANK() OVER (ORDER BY post_author_count.total_posts DESC) AS posting_rank
FROM
(
SELECT COUNT(*) AS total_posts, author_id
FROM posts
GROUP BY author_id
) post_author_count
3。总结
最后一步是将users 表与posting_rank_stats 表连接以获得结果。由于我们只想进入帖子最多的 TOP 10 用户,因此您需要添加条件
posting_rank_stats.posting_rank <= 10 在WHERE 子句中
应用相同的概念也可以获得评论排名。
这里是db fiddle I created, combine both posting rank and commenting rank
SELECT users.id , users.fullname, posting_rank_stats.posting_rank , posting_rank_stats.total_posts, commenting_rank_stats.comment_rank, commenting_rank_stats.total_comments
FROM users
LEFT JOIN
(
SELECT author_id, total_posts, RANK() OVER (ORDER BY post_author_count.total_posts DESC) AS posting_rank
FROM
(
SELECT COUNT(*) AS total_posts, author_id
FROM posts
GROUP BY author_id
) post_author_count
) posting_rank_stats ON users.id = posting_rank_stats.author_id
LEFT JOIN
(
SELECT author_id, total_comments, RANK() OVER (ORDER BY comment_author_count.total_comments DESC) AS comment_rank
FROM
(
SELECT COUNT(*) AS total_comments, author_id
FROM comments
GROUP BY author_id
) comment_author_count
) commenting_rank_stats ON users.id = commenting_rank_stats.author_id;
| id |
fullname |
posting_rank |
total_posts |
comment_rank |
total_comments |
| 1 |
Jackson |
1 |
3 |
5 |
1 |
| 2 |
Marry |
4 |
1 |
1 |
5 |
| 3 |
Josh |
4 |
1 |
2 |
3 |
| 4 |
Harley |
1 |
3 |
4 |
2 |
| 5 |
Gordon |
4 |
1 |
5 |
1 |
| 6 |
Barney |
4 |
1 |
2 |
3 |
| 7 |
Gman |
4 |
1 |
|
|
| 8 |
Stephan |
3 |
2 |
|
|
| 9 |
Lucy |
|
|
|
|
| 10 |
Jordan |
|
|
|
|
| 11 |
Bill |
|
|
|
|
| 12 |
Rosh |
|
|
|
|
| 13 |
Lee |
|
|
|
|