MySQL combine select with sum from other table(MySQL将select与其他表中的sum结合起来)
问题描述
我不是很喜欢 MySQL,但我只需要一个声明,我非常感谢您在这方面的帮助.
i'm not really much into MySQL, but i need just one statement and I would really appreciate your help on this.
我有两个表:'user' 和 'score'
I have two tables: 'user' and 'score'
这是用户"的结构:
| user_id | user_name |
| 1 | Paul |
| 2 | Peter |
这是'score'的结构:
here's the structure of 'score':
| score_id | score_user_id | score_track_id | score_points |
| 1 | 2 | 23 | 200 |
| 2 | 2 | 25 | 150 |
现在我需要一个能够为我提供某种高分列表的查询.结果应包含 user_id、user_name 和与用户相关的所有分数的总和:我应该如下所示:
now I need a query that provides me some kind of highscore-list. the result should contain user_id, user_name and the sum of all scores that are related to the user: i should look like this:
| user_id | user_name | scores |
| 1 | Paul | 0 |
| 2 | Peter | 350 |
如果将结果按照用户在全球排名中的位置排序,则更好:
even better would be, if the result would be sorted in order of the users position in the global ranking like this:
| 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.
which results in a syntax error. the main problem for me is to connect the user_id from 'user' to the score_user_id in 'score' for each row.
非常感谢您的帮助
推荐答案
你只需要将你的分数按用户分组:
You just need to group your scores by user:
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 上查看它.
这篇关于MySQL将select与其他表中的sum结合起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL将select与其他表中的sum结合起来
基础教程推荐
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
