Mysql 优化查询以显示重复客户
我正在使用prestashop 1.5,下面的查询显示了上一年与下一年的重复客户Mysql 优化查询以显示重复客户,mysql,prestashop,sqlperformance,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
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;
我想知道是否有更好的方法来优化这个查询?我正在考虑每年创建一个视图,从而最大限度地减少行数。但我不确定它是否有更好的性能
有谁能给我一个更好的解决办法吗
编辑1
我认为您可以使用条件聚合:
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;
感谢您的建议,该查询还包括非重复客户,即客户X在2013年进行的交易,但不是在2014年。当然,除非我将您的查询视为嵌套的select and add Where子句,例如Where cnt_2014>0和cnt_2015>0。您只需在“2014-01-01”和“2015-12-31”之间添加和o.invoice_日期。很抱歉,它仍然没有返回正确的结果,或者我在这里遗漏了一些内容。见我的编辑。@JeremyRIrawan。我不知道结果出了什么问题。如果您只希望客户在这两个年份购买,您可以始终添加cnt_2014>0和cnt_2015>0。