php - MySQL将select与其他表的sum结合起来

标签 php mysql sql select sum

我对 MySQL 不是很了解,但我只需要一个声明,非常感谢您对此的帮助。

我有两个表:'user' 和 'score'

这是“用户”的结构:

| user_id | user_name |
| 1       | Paul      |
| 2       | Peter     |

这是'score'的结构:

| score_id | score_user_id | score_track_id | score_points | 
| 1        | 2             | 23             | 200          |
| 2        | 2             | 25             | 150          |

现在我需要一个能为我提供某种高分列表的查询。结果应包含 user_id、user_name 以及与用户相关的所有分数的总和:我应该如下所示:

| user_id | user_name | scores |
| 1       | Paul      | 0      |
| 2       | Peter     | 350    |

如果结果按照用户在全局排名中的位置排序,那就更好了:

| position | user_id | user_name | scores |
| 1        | 2       | Peter     | 350    |
| 2        | 1       | Paul      | 0      |

我试过这个语句

SELECT user_id as current_user, user_name, SUM(SELECT score_points FROM score WHERE score_user_id = current_user) as ranking FROM user ORDER BY ranking DESC

这会导致语法错误。 对我来说,主要问题是将每一行的“user”中的 user_id 连接到“score”中的 score_user_id。

非常感谢你的帮助

最佳答案

您只需要按用户对分数进行分组:

SELECT @p:=@p+1 AS position, t.*
FROM (
  SELECT   user.user_id,
           user.user_name,
           IFNULL(SUM(score.score_points),0) AS total_points
  FROM     user LEFT JOIN score ON user.user_id = score.score_user_id
  GROUP BY user.user_id
  ORDER BY total_points DESC
) AS t JOIN (SELECT @p:=0) AS initialisation

查看 sqlfiddle .

关于php - MySQL将select与其他表的sum结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11241952/

相关文章:

SQL - 我想不出任何方法来做到这一点,我已经完成了所有研究?

php - 匹配 SQL 列并将其解析到另一个 SQL 表中

mysql - 如何在连接中使用 NOT?

php - 从 PHP 的输入中获取特定的数组值

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php - 将选定的日期值传递给查询

php mysql 和移动客户端,显示从 UTC 到不同时区的日期

php - 是否值得缓存简单的 MySQL 结果

php - 如果 mysql_query 失败则执行多条语句

PHP+MySQL,按类别输出结果