处理 group by 查询速度慢的问题
实际项目中因表数据量大,发现查询速度很慢。记录此次排查和优化过程。
希望对阅读到此文章的朋友有所帮助。
表名:packet_buy_report,数据表的总记录数 17235162 条。
该表包含的字段:
`id` varchar(36) NOT NULL,
`log_time` bigint(20) unsigned DEFAULT NULL,
`device_id` int(11) DEFAULT NULL,
`stb_id` int(11) DEFAULT NULL,
`region_id` int(11) unsigned DEFAULT NULL,
`product_id` int(11) NOT NULL,
`product_name` varchar(40) DEFAULT NULL,
`start_time` bigint(20) unsigned DEFAULT NULL,
`end_time` bigint(20) unsigned DEFAULT NULL,
`action` int(11) DEFAULT NULL,
SQL 的业务目标 : 查询设备和产品最近的日志时间,查询的 SQL 语句如下:
select device_id,product_id,max(log_time)
from packet_buy_report
GROUP BY device_id,product_id;
优化前,此表只对 device_id 和 product_id 字段设置了联合索引。执行此
SQL 耗时近 40 分钟。
一直纠结不知道什么原因导致。开始想的应该只需要对 group by 用到的字段
加索引就行,感觉加索引没什么效果。接着用 count(*)语句进行测试,SQL 如
下:
select device_id,product_id,count(*)
from packet_buy_report
GROUP BY device_id,product_id;
结果执行此 SQL 的速度提高很多倍。只耗时 46 秒。
于是推测出索引应该与字段 log_time 有关。于是将
device_id,product_id,log_time 三个字段作联合索引。然后再执行 SQL:
select device_id,product_id,max(log_time)
from packet_buy_report
GROUP BY device_id,product_id;
结果耗时 48 秒。比优化前的查询速度提高了很多倍。
总结:
对与 group by 查询的数据表。除了对 group by 直接用到的字段设置联合
索引外,还需将 SQL 中的聚合函数(如 min,max 等)用到的字段一起设置
为联合索引。如本实例中的 device_id,product 和 log_time(max 函数用
评论0