2015-11-23 30 views
0

假设我有以下几个相当大的表(350+万行):MySQL:选择所有不同的记录,选择具有最新时间戳的记录以查找重复记录?

Create table test(
col1 int, -- there is an index on this column 
col2 datetime, 
... 
... 

) 

有时候我希望能拉却只对阵COL1的记录,因为有重复,我只希望与个位最新的时间戳。

例如:

select * from test where col1 in (123, 389, 192) AND only give me the record for each match against col1 that has the latest timestamp. 

所以包含表:

123, 2015-08-23,.... 
123, 2015-09-23,.... 

它将只返回第二个记录为其中有2015年9月23日的日期值123。

感谢

回答

1

使用派生表来获得max日期为每个col1,结果加入回主表。

select t.* 
from test t 
join (select col1, max(col2) as maxdate from test group by col1) t1 
on t1.col1 = t.col1 and t1.maxdate = t.col2 
where t.col1 in (123, 389, 192) 
+0

我应该可能把这个问题放在这个问题上,但是这个表格可能会变得很大(3.5亿行),所以我会担心这个连接的性能。 –