我的表格结构如下:
我正在尝试为每位玩家选择最新的差点,因此按日期和玩家ID排序。
考虑以下问题:
SELECT h.id, h.playerId, h.amount, h.date
FROM hancicap h
WHERE h.date < '2012-06-11'
ORDER BY h.playerId ASC, h.date DESC
产生如下结果:
(带下划线的行是我想要返回的行)
我的第一个想法是添加GROUP BY h.playerId
,但这会导致错误的价值。我完全陷入困境,并会感激所有的建议和想法!
我不确定我应该为这个帖子命名。使名称更正确的编辑会很棒。
答案 0 :(得分:4)
您可以使用子查询过滤掉最新的行:
select *
from players p1
where p1.id =
(
select id
from players p2
where p2.playerId = p1.playerId
order by
date desc
limit 1
)
答案 1 :(得分:1)
如果在键上定义连接(已经有索引),则连接总是更快。
SELECT a.*
FROM hancicap a
LEFT JOIN hancicap b
ON a.playerId = b.playerId
AND a.date < b.date
AND ( a.date < '2012-06-11'
OR b.date < '2012-06-11' )
WHERE b.playerId IS NULL
答案 2 :(得分:0)
SELECT h.id, h.playerId, h.handicap, h.date
FROM handicap h
WHERE h.date < '2012-06-11'
and h.date = (SELECT max(h2.date) FROM handicap h2
WHERE h2.date < '2012-06-11' and h.playerId = h2.playerId)
我的测试数据是:
id playerId handicap date
----------- ----------- ----------- ----------
1 1 2 2012-06-05
2 1 3 2012-06-07
3 1 1 2012-06-08
4 1 12 2012-06-13
5 2 1 2012-06-09
6 2 4 2012-06-01
7 2 5 2012-06-10
(7 row(s) affected)
id playerId handicap date
----------- ----------- ----------- ----------
7 2 5 2012-06-10
3 1 1 2012-06-08
(2 row(s) affected)