查询效率 - 计数

时间:2016-12-22 06:25:57

标签: mysql performance count

我试图让查询更有效地运行并返回有效结果。当我在特定列上包含COUNT函数时,我当前的查询需要10多分钟才能完成。我还注意到在进行计数时,所有结果都返回为NULL。

当我在其上运行COUNT部分时,完成所需的时间不到一秒,我得到了正确的结果。

以下是我正在使用的查询:

 SELECT 
    x.entityCode 'Entity Code'
,   (SELECT MAX(visit_date) AS secMaxDate FROM z_dev.entities_visited 
            WHERE entity_code = x.entityCode AND visit_date < x.maxDate) ' Previous Visit Date'
,   x.maxDate   'Latest Visit Date'
,   cycle_end_date 'Cycle End Date'
,   total_visits 'Total Visits (28 Days)'
FROM 
    (SELECT 
        entity_code AS storeCode
    ,   MAX(visit_date) AS maxDate
    ,   MAX(cycle_end_date) AS cycle_end_date
    ,   (SELECT COUNT(visit_date) FROM z_dev.entities_visited A
            WHERE visit_date BETWEEN DATE(DATE_SUB(CURDATE(), INTERVAL 28 DAY)) AND DATE(DATE_SUB(CURDATE(), INTERVAL 0 DAY) AND A.entity_code = B.entity_code)
            GROUP BY entity_code) AS 'total_visits'
    FROM 
        z_dev.entities_visited B GROUP BY entity_code) AS X;

示例数据

entity_code | visit_date | cycle_end_date   
------------+------------+--------------- 
108792      |2016-12-07  |2016-12-11    
108793      |2016-12-08  |2016-12-11    
108795      |2016-12-06  |2016-12-11    
108796      |2016-12-05  |2016-12-11    
108795      |2016-12-13  |2016-12-18    
108792      |2016-12-14  |2016-12-18    
108793      |2016-12-14  |2016-12-18    
108796      |2016-12-16  |2016-12-18



   Field            | Type      | Key   
    ----------------+-----------+--------------- 
    entity_code     |bigint(10) |MUL  
    visit_date      |date       |    
    cycle_end_date  |date       |MUL    

总访问次数是我添加到昨天协助的查询解决方案中的一部分。基本上我想看到的是以下三件事:

  • 实体访问的最后日期是什么时候(目前由 x.maxDate)
  • 该实体最近一次访问的时间是最近的 访问(目前由以前访问日期&#39;提供)
  • 过去28天内访问过的实体次数

当前遇到的问题/结果

  • 慢查询时间(10分钟+)
  • 计为子查询返回所有NULL值
  • 运行计数查询,并在几秒钟内返回预期结果
  • 主查询会在几秒钟内返回预期结果

1 个答案:

答案 0 :(得分:0)

谢谢,我想我一直在想这个问题,这就是为什么我没有得到理想的结果。

我现在按预期运行查询。

SELECT 
    x.entityCode 'Entity Code'
,   (SELECT MAX(visit_date) AS secMaxDate FROM z_dev.entities_visited 
            WHERE entity_code = x.entityCode AND visit_date < x.maxDate) ' Previous Visit Date'
,   x.maxDate   'Latest Visit Date'
,   cycle_end_date 'Cycle End Date'
,   visits 'Total Visits (28 Days)'
FROM 
    (SELECT 
        entity_code AS entityCode
    ,   MAX(visit_date) AS maxDate
    ,   MAX(cycle_end_date) AS cycle_end_date
    ,   (SELECT COUNT(visit_date) AS visits WHERE visit_date BETWEEN DATE(DATE_SUB(CURDATE(), INTERVAL 28 DAY)) AND DATE(DATE_SUB(CURDATE(), INTERVAL 0 DAY))) AS visits
    FROM 
        z_dev.entities_visited B GROUP BY entity_code) AS X
GROUP BY
    x.entityCode;