简体   繁体   English

MySQL查询意外结果

[英]MySQL Query Unexpected Results

I am trying to run a MySQL query to return some information about the highest score for a group of games. 我正在尝试运行MySQL查询以返回有关一组游戏的最高分的一些信息。 The table is setup with the following columns in it: scoreid, score, gameid, playerid, date. 该表格设置为包含以下列:scoreid,score,gameid,playerid,date。 When I run the following SQL command it gives me the proper high score but returns the first submitted playerid and date. 当我运行以下SQL命令时,它给了我适当的高分,但返回第一个提交的playerid和日期。 What am I doing wrong here? 我在这做错了什么?

SELECT date, MAX(score) as score, scoreid, playerid FROM scores GROUP BY gameid

The MAX(score) won't get the row that has the max score. MAX(得分)不会获得具有最高分数的行。 It will simply return the max score, but all the other fields can simply belong to another row. 它只会返回最大分数,但所有其他字段可以简单地属于另一行。

You can better try: 你可以更好地尝试:

SELECT date, score, scoreid, playerid FROM scores GROUP BY gameid HAVING score = MAX(score)

You are grouping by gameid, but you are returning some non-aggregated columns ( date , scoreid , playerid ). 你被游戏ID分组,但你正在返回一些非聚集列( datescoreidplayerid )。 MySQL allows you to select non-aggregated columns in a group by query, but the value of those columns will be undetermined (it will usually return the first encountered value, but this is not documented and you can't rely on it). MySQL允许您通过查询选择组中的非聚合列,但这些列的值将不确定(它通常会返回第一个遇到的值,但这没有记录,您不能依赖它)。 Score is aggregated (you are using MAX() which is an aggregation function) so its value will be correct. Score是聚合的(您正在使用MAX()这是一个聚合函数),因此它的值是正确的。

If you want to return all rows that have the maximum score you should use a query like this: 如果要返回具有最高分数的所有行,则应使用如下查询:

SELECT date, score, scoreid, playerid
FROM   scores
WHERE  score = (SELECT MAX(score) FROM scores)

or if you want to return the rows that have the maximum score for every gameid, something like this: 或者如果你想返回每个gameid具有最高分数的行,如下所示:

SELECT date, score, scoreid, playerid
FROM   scores
WHERE  (gameid, score) IN (SELECT gameid, MAX(score) FROM scores GROUP BY gameid)

Please see fiddle here . 请看这里的小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM