具有日期范围的mySQL查询,并仅为每个ID选择最新记录

时间:2011-10-11 09:51:24

标签: mysql

我有下表:

Record   ID   Status     Date          Timestamp
----------------------------------------------------------
1        1    waiting    2010-02-02    2010-02-02 12:00:00
2        1    finished   2010-02-02    2010-02-02 12:30:00
3        2    waiting    2009-02-02    2009-02-02 12:00:00

我想获取日期在2010-01-01和2010-03-03之间的记录。 (这应该给我记录1和2)

此外,我想为每个ID仅获取最新的(具有最新时间戳)。 (这应该只给我记录2)。

我不确定如何构建查询。我已设法构建以下查询:

SELECT   `Record` `ID`, MAX(  `Timestamp` ) 
FROM     `myTable` 
WHERE    `Date` 
BETWEEN  '2010-01-01'
AND      '2011-03-03'
GROUP BY `ID` 

上述查询的问题在于,由于某种原因,它给出了以下结果:

Record   ID   Timestamp
---------------------------------
1        1    2010-02-02 12:30:00

这是正确的,除了Record字段的值应为2而不是1.

2 个答案:

答案 0 :(得分:3)

SELECT t1.* 
FROM `myTable` t1
INNER JOIN
(
SELECT MAX(`Timestamp`) as Timestamp
FROM     `myTable`
WHERE    `Date` 
BETWEEN  '2010-01-01'
AND      '2011-03-03'
GROUP BY `ID` 
) t2
ON t1.Timestamp = t2.Timestamp

答案 1 :(得分:0)

尝试以下查询

SELECT   `Record` `ID`,Timestamp
FROM     `myTable` 
WHERE    `Date` 
BETWEEN  '2010-01-01'
AND      '2011-03-03'
Order by `Timestamp` desc
limit 1