0

我正在将查询写入跟踪运动比赛结果的数据库。我的数据库有一个运动员表:

| id    | first_name    | last_name    | Gender  |
| 1     | Sam           | Johnson      | m       |
| 2     | Adam          | Jones        | m       |

和结果表

| id    | time          | athlete_id   
| 1     | 1302          | 1            
| 2     | 1420          | 1            
| 3     | 1491          | 2
| 4     | 1541          | 2
| 5     | 0             | 1

我想检索所有运动员,并且只检索他们最快的结果。我有这样的查询

 select a.id as aid, a.`first`, a.`last`, r.`id` as `rid`, min(r.`time`) as `time`
 FROM athletes a, results r 
 WHERE 
   r.athlete_id=a.id AND
   r.time > 0
 GROUP BY a.id
 ORDER BY r.time

到目前为止,我的查询确实将结果限制在最快的时间,但它没有按时间正确排序。我还尝试添加对结果表的第二个引用

 select a.id as aid, a.`first`, a.`last`, r.`id` as `rid`, r.`time`
 FROM athletes a, results r, results r2
 WHERE 
   r.athlete_id=a.id AND
   r2.athlete_id=a.id AND
   r.time > 0
   r1.time < r2.time
 ORDER BY r.time

但这会导致内存不足错误。结果表有超过一百万个条目,运动员条目有超过 15,000 个。所以问题仍然存在,是否有一种有效的方法对分组记录进行排序,或者我应该让 PHP 脚本在记录集循环时删除结果。

4

1 回答 1

1

尝试

SELECT q.athlete_id aid, a.first, a.last, r.id rid, q.`time`
  FROM
(SELECT athlete_id, MIN(`time`) `time`
  FROM results
 WHERE time > 0
 GROUP BY athlete_id) q JOIN results r
    ON q.athlete_id = r.athlete_id 
   AND q.`time` = r.`time` JOIN athletes a
    ON q.q.athlete_id = a.id
 ORDER BY q.`time`

输出:

| AID | FIRST |    LAST | RID | TIME |
--------------------------------------
|   1 |   Sam | Johnson |   1 | 1302 |
|   2 |  Adam |   Jones |   3 | 1491 |

SQLFiddle

于 2013-05-14T04:31:27.220 回答