-1

我为高尔夫记分卡做了一个网站。我正在处理的页面是玩家资料。当您访问球员资料时,它会按最后参加的顺序 (DESC) 显示每门课程。除了,由于下面的 ORDER BY 命令,最后播放的顺序是混乱的。相反,当它分组时,它采用最早的日期,而不是最近的日期。

分组完成后,它会按顺序正确显示它们(DESC)......由于课程按 date_of_game ASC 而不是 DESC 分组,因此顺序错误。希望这不会太令人困惑..谢谢。

$query_patrol321 = "SELECT t1.*,t2.* FROM games t1 LEFT JOIN scorecards t2 ON t1.game_id=t2.game_id WHERE t2.player_id='$player_id' GROUP BY t1.course_id ORDER BY t1.date_of_game DESC";
$result_patrol321 = mysql_query($query_patrol321) or die ("<br /><br />There's an error in the MySQL-query: ".mysql_error());
while ($row_patrol321 = mysql_fetch_array($result_patrol321)) {
    $player_id_rank = $row_patrol321["player_id"];
    $course_id = $row_patrol321["course_id"];
    $game_id = $row_patrol321["game_id"];
    $top_score = $row_patrol321["total_score"];
4

3 回答 3

2

尝试从查询中删除 GROUP BY 子句。只有在 SELECT 中同时具有普通列和聚合函数(min、max、sum、avg、count)时,才应该使用 GROUP BY。你只有普通的列。

于 2013-05-01T17:22:08.497 回答
0

如果您想要最大日期,请插入逻辑来获取它。不要依赖于列的顺序或未记录的 MySQL 特性。MySQL 明确不鼓励在值不相同时使用非聚合列group by

MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. This means that the preceding query is legal in MySQL. You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate.  (see [here][1])

你怎么做你想做的事?以下查询查找每门课程的最新日期,并仅使用该日期 -- 和 no group by

SELECT t1.*, t2.*
FROM games t1 LEFT JOIN
     scorecards t2
     ON t1.game_id=t2.game_id
WHERE t2.player_id='$player_id' and
      t1.date_of_game in (select MAX(date_of_game)
                          from games g join
                               scorecards ss
                               on g.game_id = ss.game_id and
                                  ss.player_id = '$player_id'
                          where t1.course_id = g.course_id
                         )
GROUP BY t1.course_id
ORDER BY t1.date_of_game DESC

如果game_id是自动递增,您可以使用它而不是date_of_game. 如果两场比赛可以在同一日期在同一球场进行,这一点尤其重要。

于 2013-05-01T18:04:04.327 回答
0

它按顺序显示分组结果的事实ASC是巧合,因为这是它们插入的顺序。与 MS SQL Server 等其他 RDBMS 相比,MySQL 允许您向GROUPed 查询添加非聚合列。这种非标准行为会造成您所看到的混乱。如果这不是 MySQL,您需要为给定分组的所有选定列定义聚合。

GROUPMySQL 的行为是(我相信)获取与非聚合列匹配的第一行。我建议不要这样做。

即使您正在聚合,您也不会ORDER按聚合列。

所以你想做的ORDER BYMAX日期DESC

这样,您将按每门课程的最新日期(您的分组标准)进行排序。

SELECT 
    t1.* -- It would be better if you actually listed the aggregations you wanted
    ,t2.* -- Which columns do you really want?
FROM 
    games t1 
LEFT JOIN 
    scorecards t2 
        ON t2.[game_id] =t1[.game_id]
WHERE 
    t2.[player_id]='$player_id' 
GROUP BY 
    t1.[course_id] 
ORDER BY 
    MAX(t1.[date_of_game]) DESC
于 2013-05-01T17:32:56.827 回答