MySQL查询帮助 - 上次已知的测试日期和当前测试日期

时间:2013-07-29 15:28:18

标签: php mysql sql

我有一个MySQL表,其中包含基准测试......

benchmarkid     playerid         verified     benchmark  resultnumber   testdate  

1               70               1            40msprint  6.0            2013-06-03      
2               70               1            40msprint  6.1            2013-06-04      
3               70               1            40msprint  6.3            2013-06-05  
4               71               1            40msprint  6.0            2013-06-03      
5               71               1            40msprint  6.1            2013-06-04      
6               71               1            40msprint  6.3            2013-06-05  

我想查询该表,其中包含基准测试日期" 40msprint"获取该日期的当前结果以及当时每个玩家的最后已知结果。

例如,在2013-06-04,对于经过验证的= 1个40ms的玩家70和71,它看起来就像。

playerid    currentresult       previousresult  previousdate        
70          6.1                     6.0         2013-06-03      
71          6.1                     6.0         2013-06-03  

我也会知道我想找到的玩家,一次只能看到20个。

MySql查询的任何想法会让我这么做?

1 个答案:

答案 0 :(得分:0)

鉴于此测试数据:

CREATE TABLE Table1
    (`benchmarkid` int, `playerid` int, `verified` int, `benchmark` varchar(9), `resultnumber` decimal(5,2), `testdate` date)
;

INSERT INTO Table1
    (`benchmarkid`, `playerid`, `verified`, `benchmark`, `resultnumber`, `testdate`)
VALUES
    (1, 70, 1, '40msprint', 6.0, '2013-06-03'),
    (2, 70, 1, '40msprint', 6.1, '2013-06-04'),
    (3, 70, 1, '40msprint', 6.3, '2013-06-05'),
    (4, 71, 1, '40msprint', 6.0, '2013-06-03'),
    (5, 71, 1, '40msprint', 6.1, '2013-06-04'),
    (6, 71, 1, '40msprint', 6.3, '2013-06-05'),
    (7, 70, 1, '40msprint', 6.1, '2013-06-06'),
    (8, 71, 1, '40msprint', 6.1, '2013-06-06'),

    (9, 71, 1, '40msprint', 6.3, '2013-06-02'),
    (10, 70, 1, '40msprint', 6.1, '2013-06-02')
;

此查询有效:

select
t1.testdate as date,
t1.playerid,
t1.resultnumber,
t2.testdate as previous_date,
t2.resultnumber as previous_result
from
Table1 t1
left join Table1 t2 on t1.testdate > t2.testdate and t1.playerid = t2.playerid
where
t1.testdate = '2013-06-05'
and t2.testdate = (SELECT MAX(testdate) FROM Table1 WHERE Table1.testdate < t1.testdate)

结果:

|                        DATE | PLAYERID | RESULTNUMBER |               PREVIOUS_DATE | PREVIOUS_RESULT |
---------------------------------------------------------------------------------------------------------
| June, 05 2013 00:00:00+0000 |       70 |          6.3 | June, 04 2013 00:00:00+0000 |             6.1 |
| June, 05 2013 00:00:00+0000 |       71 |          6.3 | June, 04 2013 00:00:00+0000 |             6.1 |