簡體   English   中英

MySQL將select與來自其他表的sum結合起來

[英]MySQL combine select with sum from other table

我對MySQL並不是很了解,但我需要一個聲明,我非常感謝你對此的幫助。

我有兩張桌子:'用戶'和'得分'

這是“用戶”的結構:

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

這里是'得分'的結構:

| 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_id從'user'連接到每行的'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上看到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM