优化代码SELECT SUM(IF(order_date BETWEEN '2021-11-01' AND '2021-11-15', 1, 0)) AS new_customer_count, SUM(IF(order_date BETWEEN '2021-11-01' AND '2021-11-15', amount, 0)) AS new_customer_amount, SUM(IF(order_date BETWEEN '2021-11-01' AND '2021-11-15' AND o1.customer_id IS NOT NULL, 1, 0)) AS old_customer_count, SUM(IF(order_date BETWEEN '2021-11-01' AND '2021-11-15' AND o1.customer_id IS NOT NULL, amount, 0)) AS old_customer_amount FROM orders o LEFT JOIN ( SELECT customer_id FROM orders WHERE order_date < '2020-11-01' ) o1 ON o.customer_id = o1.customer_id WHERE order_date BETWEEN '2021-11-01' AND '2021-11-15'
时间: 2024-01-24 12:18:03 浏览: 81
SQL-define-sum.rar_SUM
这段 SQL 代码看起来已经很优化了,但是如果要进一步优化,可以考虑以下几点:
1. 使用索引:为了提高查询效率,可以在 order_date 和 customer_id 字段上创建索引。
2. 简化 IF 语句:可以将 IF(order_date BETWEEN '2021-11-01' AND '2021-11-15', 1, 0) 简化为 (order_date BETWEEN '2021-11-01' AND '2021-11-15'),同样的方法也可以用于其他 IF 语句。
3. 使用子查询的优化:可以使用 EXISTS 或 IN 替换掉子查询,以提高查询效率。
优化后的 SQL 代码如下:
SELECT
SUM(order_date BETWEEN '2021-11-01' AND '2021-11-15') AS new_customer_count,
SUM(IF(order_date BETWEEN '2021-11-01' AND '2021-11-15', amount, 0)) AS new_customer_amount,
SUM(order_date BETWEEN '2021-11-01' AND '2021-11-15' AND o1.customer_id IS NOT NULL) AS old_customer_count,
SUM(IF(order_date BETWEEN '2021-11-01' AND '2021-11-15' AND o1.customer_id IS NOT NULL, amount, 0)) AS old_customer_amount
FROM orders o
LEFT JOIN (SELECT DISTINCT customer_id FROM orders WHERE order_date < '2020-11-01') o1 ON o.customer_id = o1.customer_id
WHERE order_date BETWEEN '2021-11-01' AND '2021-11-15';
其中,使用了 DISTINCT 关键字来去重,以替换掉子查询。
阅读全文