mysql query execution consuming time

时间:2017-06-15 09:41:26

标签: mysql

I have seen several question in SO and based in that I improved my sql query also. but it sometime take 12 second or it sometime takes 3 seconds to execute. so minimum time we can its 3 seconds. query is like this way

SELECT ANALYSIS.DEPARTMENT_ID
    ,SCORE.ID
    ,SCORE.KPI_ SCORE.R_SCORE
    ,SCORE.FACTOR_SCORE
    ,SCORE.FACTOR_SCORE
    ,SCORE.FACTOR_SCORE
    ,SCORE.CREATED_DATE
    ,SCORE.UPDATED_DATE
FROM SCORE_INDICATOR SCORE
    ,AG_SENTIMENT ANALYSIS
WHERE SCORE.TAG_ID = ANALYSIS.ID
    AND ANALYSIS.ORGANIZATION_ID = 1
    AND ANALYSIS.DEPARTMENT_ID IN (1,2,3,4,5)
    AND DATE (ANALYSIS.REVIEW_DATE) BETWEEN DATE ('2016-05-02') AND DATE ('2017-05-02')
ORDER BY ANALYSIS.DEPARTMENT_ID

now one table SCORE_INDIACATOR has 19345116 and later has 19057025 rows total. and I added index on ORGANIZATION_ID and department_id and another as combination of ORGANIZATION_ID and department_id . is there any other way to improve it or is it maximum I can achieve with this amount of data?

2 个答案:

答案 0 :(得分:1)

这是清单:

1)确保日志表(ANALYSIS)使用MyISAM引擎(对于OLAP查询来说速度很快)。

2)确保您已将ANALYSIS.REVIEW_DATE字段编入索引。

3)确保ANALYSIS.REVIEW_DATE的类型为DATE(不是CHARVARCHAR

4)更改查询(重新排列查询计划):

SELECT 
    ANALYSIS.DEPARTMENT_ID
    ,SCORE.ID
    ,SCORE.KPI_ SCORE.R_SCORE
    ,SCORE.FACTOR_SCORE
    ,SCORE.FACTOR_SCORE
    ,SCORE.FACTOR_SCORE
    ,SCORE.CREATED_DATE
    ,SCORE.UPDATED_DATE
FROM SCORE_INDICATOR SCORE
    ,AG_SENTIMENT ANALYSIS
WHERE 
    SCORE.TAG_ID = ANALYSIS.ID 
  AND
    ANALYSIS.REVIEW_DATE >= '2016-05-02' AND ANALYSIS.REVIEW_DATE < '2016-05-03'
  AND
    ANALYSIS.ORGANIZATION_ID = 1
  AND 
    ANALYSIS.DEPARTMENT_ID IN (1,2,3,4,5)
ORDER BY ANALYSIS.DEPARTMENT_ID;

答案 1 :(得分:1)

我已将订单和样式更改为JOIN语法。 Score表似乎是Analysis表的主要标准的子项。您的所有条件都基于合格的分析记录。现在,索引。通过对列进行DATE()函数调用对优化器没有帮助。因此,为了获得所有可能的日期/时间组件,我已经从中间更改为&gt; =第一个日期,并且比结束日期还要少一天。在您的示例中,DATE(&#39; 2017-05-02&#39;)与LESS相同,而不是&#39; 2017-05-03&#39;其中包括截至23:59:59的2017-05-02,日期可以更好地应用。

现在为索引。根据加入和排序的字段做一个复合索引可能会有帮助

AG_Segment表...索引ON(Organization_ID,Department_ID,Review_Date,ID)

SELECT 
        ANALYSIS.DEPARTMENT_ID,
        SCORE.ID,
        SCORE.KPI_ SCORE.R_SCORE,
        SCORE.FACTOR_SCORE,
        SCORE.FACTOR_SCORE,
        SCORE.FACTOR_SCORE,
        SCORE.CREATED_DATE,
        SCORE.UPDATED_DATE
    FROM 
        AG_SENTIMENT ANALYSIS
            JOIN SCORE_INDICATOR SCORE
                ON ANALYSIS.ID = SCORE.TAG_ID
    where 
            ANALYSIS.ORGANIZATION_ID = 1
        AND ANALYSIS.DEPARTMENT_ID IN (1,2,3,4,5)
        AND ANALYSIS.REVIEW_DATE >= '2016-05-02'
        AND ANALYSIS.REVIEW_DATE < '2017-05-03'
    ORDER BY 
        ANALYSIS.DEPARTMENT_ID