我在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只有一个不同的athleteId。目前,如果两个项目的最佳表现是由同一个运动员完成的,则该运动员将在输出中出现两次。如果发生这种情况,我需要表现第二好的运动员出现,而不是第一。
简称:一名运动员不能出现两次。
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

最佳答案

下面是如何在调用者代码(本例中为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);
}

关于mysql - 如何撰写MySQL查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14073779/

10-15 18:29
查看更多