我建立了一个高尔夫记分卡网站。我正在处理的页面是玩家档案。当您访问玩家资料时,它会按照上次播放的顺序显示每个课程(DESC)。除此之外,由于下面的ORDER BY命令,上次播放的顺序是混乱的。相反,当它为GROUP时,它需要最早的日期,而不是最近的日期。
分组完成后,它会按顺序正确显示它们(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"];
答案 0 :(得分:2)
尝试从查询中删除GROUP BY子句。只有在SELECT中同时具有普通列和聚合函数(min,max,sum,avg,count)时,才应使用GROUP BY。你只有普通的列。
答案 1 :(得分:0)
它以ASC
顺序显示分组结果的事实是巧合,因为这是它们插入的顺序。与MS SQL Server等其他RDBMS相比,MySQL允许您将非聚合列添加到GROUP
ed查询中。这种非标准行为会造成您所看到的混乱。如果这不是MySQL,则需要为给定分组的所有选定列定义聚合。
MySQL的行为(我相信)采取与非聚合列匹配GROUP
的第一行。我建议不要这样做。
即使您正在汇总,也不是ORDER
聚合列。
那么您要做的是ORDER BY
MAX
日期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
答案 2 :(得分: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])
你怎么做你想要的?以下查询查找每个课程的最新日期,并使用该日期 - 而不是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
。如果两场比赛可以在同一天的同一场比赛中,这一点尤为重要。