2015-11-23 33 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億行),所以我會擔心這個連接的性能。 –