groupBy和orderBy的替代方案

1、背景

相关的设备状态数据

在开发的时候遇到一个需求,须要根据device_code将数据分组,同时得到每组数据中最新的一条数据。sql

2、遇到的问题

2.1 最初的思路:先对数据进行orderBy 再进行groupBy
sql语句:
 sql: SELECT * from y_device_events ORDER BY created_at DESC GROUP BY device_code

结果: 这种写法会报错,当groupBy和orderBy组合使用的时候,必需要先进性groupBy在进行orderBy。spa

2.2 进阶思路:对数据进行orderBy的结果做为临时表,再对临时表分组
sql语:
 sql:SELECT * from (SELECT * from y_device_events ORDER BY created_at DESC) as new_table GROUP BY new_table.device_code

结果:这条语句执行了,可是结果并无按照预期的将最新的一条筛选出来code

3、最终的解决方案

3.1 初级方案

经过以前两种方案发现直接使用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

这种方法经过左关联查询,对笛卡尔积进行了筛选,就能够达到咱们的目的。开发

3.2 缺点:对于数据量特别大的状况,若是没有限制条件,获得的笛卡尔积会很大,因此查询速度较慢。
3.3 最终的写法

个人需求中能够加上对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

相关文章
相关标签/搜索