2

我有一个结构如下的表:

架构图

我正在尝试为每个玩家选择最新的让分盘,因此按日期和 playerId 排序。

考虑以下查询:

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,但这会导致错误的值。我完全被困住了,不胜感激所有的建议和想法!

不确定我应该给线程命名什么。使名称更正确的编辑会很棒。

4

3 回答 3

4

您可以使用子查询过滤掉最新的行:

select  *
from    players p1
where   p1.id =
        (
        select  id
        from    players p2
        where   p2.playerId = p1.playerId
        order by
                date desc
        limit   1
        )
于 2012-06-13T07:53:04.060 回答
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 
于 2012-06-13T08:14:44.677 回答
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)
于 2012-06-13T07:56:51.530 回答