优化查询以显示重复客户

时间:2015-03-21 16:49:53

标签: mysql prestashop sqlperformance

我正在使用prestashop 1.5并且有以下查询显示重复客户(上一年与明年)。

SELECT prev.id_customer, prev.name, prev.email, prev.count AS 'prev', next.count AS 'next'
FROM(
    SELECT o.id_customer, CONCAT(c.firstname, ' ', c.lastname) AS name, c.email, COUNT(1) AS 'count'
    FROM ps_orders AS o
    LEFT JOIN ps_order_history AS h ON o.id_order = h.id_order
    LEFT JOIN ps_customer AS c on o.id_customer = c.id_customer
    WHERE o.invoice_date BETWEEN '2014-01-01' AND '2014-12-31'
    AND h.id_order_state = 2
    GROUP BY o.id_customer
    ORDER BY count DESC
) AS prev,
(
    SELECT o.id_customer, CONCAT(c.firstname, ' ', c.lastname) AS name, c.email, COUNT(1) AS 'count'
    FROM ps_orders AS o
    LEFT JOIN ps_order_history AS h ON o.id_order = h.id_order
    LEFT JOIN ps_customer AS c on o.id_customer = c.id_customer
    WHERE o.invoice_date BETWEEN '2015-01-01' AND '2015-12-31'
    AND h.id_order_state = 2
    GROUP BY o.id_customer
    ORDER BY count DESC
) AS next
WHERE prev.id_customer = next.id_customer
ORDER BY prev.name ASC;

我想知道是否有更好的方法来优化此查询?我正在考虑每年创建一个VIEW,从而最大限度地减少行数。但我不确定它是否更好(表现明智)。

有人能给我一个更好的解决方案吗?

编辑1

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为你可以使用条件聚合:

SELECT o.id_customer, CONCAT(c.firstname, ' ', c.lastname) AS name, c.email, 
       SUM(o.invoice_date BETWEEN '2014-01-01' AND '2014-12-31') as cnt_2014,
       SUM(o.invoice_date BETWEEN '2015-01-01' AND '2015-12-31') as cnt_2015
FROM ps_orders o LEFT JOIN
     ps_order_history h
     ON o.id_order = h.id_order LEFT JOIN
     ps_customer c
     on o.id_customer = c.id_customer
WHERE h.id_order_state = 2
GROUP BY o.id_customer;