1

我在 MySQL 数据库中有这个表。

-----------------tests---------------
----athleteId----eventId----score----
----129907-------1----------900------
----129907-------2----------940------
----129907-------3----------927------
----129907-------4----------856------
----328992-------1----------780------
----328992-------2----------890------
----328992-------3----------936------
----328992-------4----------864------
----492561-------1----------899------
----492561-------2----------960------
----492561-------3----------840------
----492561-------4----------920------
----487422-------5----------900------
----487422-------6----------940------
----487422-------7----------927------
----629876-------5----------780------
----629876-------6----------890------
----629876-------7----------940------
----138688-------5----------899------
----138688-------6----------950------
----138688-------7----------840------
-------------------------------------

我想要这个输出。

---------------output----------------
----eventId----athleteId----score----
----1----------129907-------900------
----2----------492561-------960------
----3----------328992-------936------
----4----------//////-------///------
----5----------487422-------900------
----6----------138688-------950------
----7----------629876-------940------

我们通过此查询部分解决了问题,但我希望每个 eventId 只有 1 个不同的运动员 ID。目前,如果 2 个项目的最佳表现由同一运动员完成,则该运动员将出现在输出中两次。如果发生这种情况,我需要出现表现第二好的运动员而不是第一名。

缩短:一名运动员不能在结果中出现两次。

SELECT athleteId, a.eventId, a.score
FROM tests AS a
JOIN (
-- This select finds the top score for each event
SELECT eventId, MAX(score) AS score
FROM tests 
GROUP BY eventId
) AS b
-- Join on the top scores
ON a.eventId = b.eventId
AND a.score = b.score
4

1 回答 1

1

以下是如何在调用者代码中执行此操作(本例中为 PHP)。

使用查询:

SELECT athleteId, eventId, score
FROM tests
ORDER BY score DESC;

然后使用下面的代码来处理查询的结果(我跳过所有的样板来执行查询):

$events = array(); // Remember events reported
$athletes = array(); // Remember athletes listed

while ($row = mysqli_fetch_assoc($results)) {
  if (isset($events[$row['eventId']]) || isset($athletes[$row['athleteId']])) {
     continue;
  }
  $events[$row['eventId']] = true;
  $athletes[$row['athleteId']] = true;
  print_row($row);
}
于 2012-12-28T18:50:10.890 回答