我有下表名为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
我如何选择最近的条目,其中日期,时间和组号相同,(第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)
上的索引,并且使用正确的索引应该非常快。
答案 1 :(得分: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