groupBy和orderBy的替代方案

一、背景

《groupBy和orderBy的替代方案》

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

二、遇到的问题

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

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

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 

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

三、最终的解决方案

3.1 初级方案

通过之前两种方案发现直接使用orderBy和groupBy并不能达到目的,最后觉得可以和自身作关联查询,通过关联查询进行筛选。

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里

 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'

加入筛选条件后,可以大大加快查询的效率。

    原文作者:早起写代码
    原文地址: https://segmentfault.com/a/1190000015490708
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞