我试图让查询更有效地运行并返回有效结果。当我在特定列上包含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
总访问次数是我添加到昨天协助的查询解决方案中的一部分。基本上我想看到的是以下三件事:
当前遇到的问题/结果
答案 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;