我有查询工作正常,但现在数据是数百万,所以获取它说服务器找不到。我想在这里比较上个月的当月和上月的客户明智的销售情况,以便我按user_id用户分组。
我看到通过查询删除组运行得更快,但输出我只希望客户明智,所以它必须在那里。
SELECT Customer.id,
Customer.first_name,
Customer.last_name,
SUM(Sale.`cal_qty`) AS totPurchase,
Sale2.tot2 as totPurchase2
FROM `customers` AS Customer
LEFT JOIN `sales` AS Sale
ON Sale.customer_id = Customer.id
LEFT JOIN (
SELECT s2.customer_id AS customer_id,
SUM(s2.cal_qty) as tot2
FROM sales as s2
WHERE s2.sale_date between '2015-07-23'
AND '2015-08-21'
GROUP BY s2.customer_id
) AS Sale2
ON Sale.customer_id = Sale2.customer_id
WHERE Sale.sale_date between '2015-08-22' AND '2015-09-21'
GROUP BY Sale.`customer_id`
having totPurchase > totPurchase2
ORDER BY totPurchase DESC
任何人都可以建议我对查询进行优化查询。
提前致谢。
答案 0 :(得分:0)
不确定,但您可以尝试以下查询,可能对您有帮助 -
注意:假设customer.id是主键或索引,sale.customer_id也被编入索引,sale.sale_date也被编入索引。
SELECT Customer.id,
Customer.first_name,
Customer.last_name,
sale1.totPurchase,
Sale2.tot2 AS totPurchase2
FROM `customers` AS Customer
JOIN
(
SELECT Sale.`customer_id`,
SUM(Sale.`cal_qty`) AS totPurchase
FROM `sales` AS Sale
WHERE Sale.sale_date BETWEEN '2015-08-22' AND '2015-09-21'
GROUP BY Sale.`customer_id`
) AS Sale1 ON Sale1.customer_id = Customer.id
LEFT JOIN
(
SELECT s2.customer_id AS customer_id,
SUM(s2.cal_qty) AS tot2
FROM sales AS s2
WHERE s2.sale_date BETWEEN '2015-07-23'
AND '2015-08-21'
GROUP BY s2.customer_id
) AS Sale2
ON Sale1.customer_id = Sale2.customer_id
HAVING totPurchase > totPurchase2
ORDER BY totPurchase DESC