今天帮运营导数据时发现sql执行速度非常慢,嗯,按照之前的编写习惯,后来跟架构师一起分析讨论,改进了下,现记录分析如下
一、测试表、sql情况
set @bgDate = '20171213'; set @edDate = '20171213'; /*编号①*/ SELECT TA_ID,SUM(TB.amount),SUM(TB.fee) FROM (SELECT ORDER_NO,TA_ID FROM Table_A WHERE TA_STATUS = 100 AND TA_CHANNEL_MERCH_NO = '201712130001' AND SETTLE_DATE <= @endDate AND SETTLE_DATE >= @begDate )TA LEFT JOIN (SELECT ORDER_NO,AMOUNT,fee FROM Table_B) TB ON TA.ORDER_NO = TB.ORDER_NO GROUP BY TA.TA_ID; /*编号②*/ SELECT TA.`TA_ID` AS TA_ID , sum(TA.`AMOUNT`) AS sumAmount , sum(TB.`fee`) AS sumMerFee FROM `Table_A` TA LEFT JOIN `Table_B` TB ON TA.`ORDER_NO` = TB.`ORDER_NO` WHERE TA.`SETTLE_DATE` >= @begDate AND TA.`SETTLE_DATE` <= @endDate AND TA.`TA_CHANNEL_MERCH_NO`='201712130001' AND TA.`TA_STATUS`=100 GROUP BY TA.`TA_ID` /*以下为表的索引情况*/ Table_A 索引:TA_ID、order_no、settle_date Table_B 索引:order_no /*以下为表的数据量情况*/ Table_A:10W+条记录 Table_B:10W+条记录
二、测试结果
①90s才出结果;
②1.5s就出结果;
三、分析
1、navicat-解释
编号①的TA进行了全表扫描;
2、自主分析
编号①sql
(1)虽然已减少了表数据量,但是由于新创了临时表TA、TB,都无索引,在left join时速度较慢;
(2)最后group by时,TA.TA_ID也无索引,导致再一次降低速度;
编号②sql
(1)虽然TA、TB直接全表left join,但是连接的order_no已做索引,速度还是能保证的;
(2)where和group by中涉及部分字段已加索引。
时间: 2024-10-10 04:36:31