2016-05-16 46 views
0

我有以下表命名classamendments,選擇最近添加的行,其中三列是相同的

+ID | date | time | groupnummber | date added  | type 
============================================================================ 
1 | 16-05-18 | 07:00  | 1    | 16/05/ 12:00:00| add 
2 | 16-05-18 | 07:00  | 1    | 16/05/ 12:05:00| rem 
3 | 16-05-18 | 07:00  | 1    | 16/05/ 12:06:00| add 
4 | 16-05-20 | 15:00  | 4    | 16/05/ 18:49:00| add 
5 | 16-05-20 | 15:00  | 4    | 16/05/ 20:10:00| rem 

我將如何選擇最新的條目,其中日期,時間和groupnumber地方一樣,(行圖3和5)

+0

你有什麼嘗試嗎? –

回答

1

一種簡單的方法使用一個相關子在where

select t.* 
from t 
where t.dateadded = (select max(t2.dateadded) 
        from t t2 
        where t2.date = t.date and t2.time = t.time and 
          t2.groupnumber = t.groupnumber 
        ); 

此查詢可以利用t(date, time, groupnumber, dateadded)上的索引,並且使用正確的索引應該相當快。

0

嘗試這種情況:

SELECT t1.* 
FROM mytable AS t1 
JOIN (
    SELECT date, time, groupnummber, MAX(date_added) AS date_added 
    FROM mytable 
    GROUP BY date, time, groupnummber 
) AS t2 ON t1.date = t2.date AND 
      t1.time = t2.time AND 
      t1.groupnummber = t2.groupnummber AND 
      t1.date_added = t2.date_added