如果我有一张存放一个人名字的桌子,他们跑一英里所花的时间,以及当他们跑了一英里的时候,什么是让一个人最近的单圈时间的最佳方式
LAPS
____________________________________________
| name | lap_time | date |
--------------------------------------------
| George | 20.3 | 2013-01-17 09:17:14 |
| Alex | 32.2 | 2013-02-17 14:24:32 |
| Mike | 16.6 | 2013-01-17 07:57:54 |
| Alex | 28.5 | 2013-01-17 19:50:21 |
| Mike | 15.1 | 2013-02-17 12:37:12 |
| Mike | 14.8 | 2013-03-17 06:58:34 |
''''''''''''''''''''''''''''''''''''''''''''
我一直这样做,到目前为止它对我有用,但我很想知道是否有更好的方法。
SELECT l.lap_time
FROM laps l
INNER JOIN(
SELECT *, MAX(date) as most_recent
FROM laps
WHERE name = 'Alex'
)AS temp ON (
l.date = temp.most_recent
AND l.name = temp.name
)
我使用此类查询的实际表格非常庞大,因此我正在寻找最有效的方法。
答案 0 :(得分:1)
这适用于单个名称:
SELECT name, lap_time, date
FROM laps
WHERE name = 'Alex'
ORDER BY date DESC
LIMIT 1
<强>结果强>
| NAME | LAP_TIME | DATE | ----------------------------------------------------- | Alex | 32.2 | February, 17 2013 14:24:32+0000 |
这适用于所有名称:
SELECT a.name, b.lap_time, a.date
FROM
(SELECT name, MAX(date) AS date FROM laps GROUP BY name) a
LEFT JOIN laps b
ON b.date = a.date AND b.name = a.name
<强>结果强>
| NAME | LAP_TIME | DATE | ------------------------------------------------------- | Alex | 32.2 | February, 17 2013 14:24:32+0000 | | George | 20.3 | January, 17 2013 09:17:14+0000 | | Mike | 14.8 | March, 17 2013 06:58:34+0000 |
答案 1 :(得分:1)
我会用这个查询测试它,用MAX来查看哪个更快。
Select * from laps where name = 'Alex' order by date desc limit 1;