首页 > 代码库 > 查询组数据中最新记录的集合

查询组数据中最新记录的集合

实例:现有一张统计表,是以task_id和start_time作为联合主键的,每一个任务可以启动多次,这样一来同一个task_id就会对应多个start_time即多条统计记录,现在要求将所有的任务统计出来,也就是查询出task_id唯一的集合,每条任务对应的是最新的一条统计记录

 1 <select id="selectLatestStatistics" resultType="com.haitao55.spider.common.dos.StatisticsDO"> 2         <!-- 方法一:使用in关键字 --> 3         select 4         <include refid="allColumns" /> 5         from statistics  6         where start_time in( 7         select max(start_time) from statistics 8         group by task_id) 9         10         <!-- 方法二:使用any_value关键字 -->11         select task_id taskId,max(start_time) startTime,any_value(end_time) endTime, 12                any_value(success_count) successCount, any_value(failed_count) failedCount,13                any_value(offline_count) offlineCount, any_value(total_count) totalCount14         from   statistics15         group by task_id16         17         <!-- 方法三:连表查询 -->18         select  a.task_id as taskId, a.start_time as startTime, a.end_time as endTime, 19                 a.success_count as successCount, a.failed_count as failedCount, 20                 a.offline_count as offlineCount, a.total_count as totalCount21         from statistics a,(22             select task_id,max(start_time) startTime23             from statistics24             group by task_id) b25         where a.task_id = b.task_id26         and a.start_time = b.startTime27     </select>

 

查询组数据中最新记录的集合