在开发的时候遇到一个需求,须要根据device_code将数据分组,同时得到每组数据中最新的一条数据。sql
sql语句: sql: SELECT * from y_device_events ORDER BY created_at DESC GROUP BY device_code
结果: 这种写法会报错,当groupBy和orderBy组合使用的时候,必需要先进性groupBy在进行orderBy。spa
sql语: sql:SELECT * from (SELECT * from y_device_events ORDER BY created_at DESC) as new_table GROUP BY new_table.device_code
结果:这条语句执行了,可是结果并无按照预期的将最新的一条筛选出来code
经过以前两种方案发现直接使用orderBy和groupBy并不能达到目的,最后以为能够和自身做关联查询,经过关联查询进行筛选。blog
SELECT `y_device_events`.* FROM `y_device_events` LEFT JOIN `y_device_events` AS `new_table` ON `y_device_events`.`device_code` = `new_table`.`device_code` AND `y_device_events`.`created_at` < `new_table`.`created_at` WHERE `new_table`.`created_at` IS NULL
这种方法经过左关联查询,对笛卡尔积进行了筛选,就能够达到咱们的目的。开发
个人需求中能够加上对type及sub_type的限制,所以稍微能够加快一下数据的筛选,并且若是有数据筛选条件,能够将条件放入JOIN语句里面,而不是join完成的where里it
SELECT `y_device_events`.* FROM `y_device_events` LEFT JOIN `y_device_events` AS `new_table` ON `y_device_events`.`device_code` = `new_table`.`device_code` AND `y_device_events`.`created_at` < `new_table`.`created_at` AND `y_device_events`.`type` = `new_table`.`type` AND `y_device_events`.`sub_type` = `new_table`.`sub_type` AND `y_device_events`.`type` = `2` AND `y_device_events`.`sub_type` = `1` WHERE `new_table`.`created_at` IS NULL AND `y_device_events`.`created_at` > '2018 - 07 - 05 10 : 07 : 27' AND `y_device_events`.`created_at` < '2018 - 07 - 05 11 : 04 : 27' AND `y_device_events`.`result_code` = '-1'
加入筛选条件后,能够大大加快查询的效率。event