mysql - 查询寻找得分最多的人

标签 mysql sql

我正在使用 Mysql 并有这些表:(只显示重要的列)

人物
id, 主键

发布
id,主键
, INT

参观
id,主键
person_id,指Person
post_id,指的是帖子

我想找到的是总体得分最高的人(前 5 名)?以及每个帖子上得分最高的人。

有人可以指导我吗?非常感谢任何帮助!

最佳答案

总分最高的前 5 名:

SELECT
    p.id,
    SUM(Post.points) AS total_points
FROM
    Person p
    INNER JOIN Visit v
        ON p.id = v.person_id
    INNER JOIN Post
        ON v.post_id = Post.id
GROUP BY
    p.id
ORDER BY
    SUM(Post.points) DESC
LIMIT 5

一篇文章中得分最多的前 5 个人:

SELECT
    p.id,
    MAX(Post.points) AS best_post_points
FROM
    Person p
    INNER JOIN Visit v
        ON p.id = v.person_id
    INNER JOIN Post
        ON v.post_id = Post.id
GROUP BY
    p.id
ORDER BY
    MAX(Post.points) DESC
LIMIT 5

前 5 个帖子:

SELECT
    p.id,
    Post.points
FROM
    Person p
    INNER JOIN Visit v
        ON p.id = v.person_id
    INNER JOIN Post
        ON v.post_id = Post.id
ORDER BY
    Post.points DESC
LIMIT 5

关于mysql - 查询寻找得分最多的人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9117518/

相关文章:

MySQL:在具有现有记录的表上添加索引

mysql - 配置本地 MySql 数据库与 grails 应用程序的连接

MySQL 格式化 YEARWEEK(日期)

php - mysql 导入到 varchar 字段包含我没有看到的内容

sql - 我正在将 348k 行数据从 Excel 导入到 VB.net SQL。我得到这个错误 : Timeout expired

mysql - SQL 连接问题和 where 子句

php - 基数违规 : 1222 The used SELECT statements have a different number of columns

mysql - 无法抓取 db :migrate because of mysql missing . frm 文件

SQL Server 在 sql 变量中存储多个值

mysql - 更新 Liquibase 时的默认值