SQL查询
SELECT
o.order_id,
o.order_date,
GROUP_CONCAT(p.product_name SEPARATOR ', ') AS product_names,
SUM(p.price * oi.quantity) AS total_amount
FROM
orders o
JOIN
order_items oi ON o.order_id = oi.order_id
JOIN
products p ON oi.product_id = p.product_id
GROUP BY
o.order_id, o.order_date
ORDER BY
total_amount DESC;
性能优化思路
- 索引策略:
- 在
orders
表的order_id
列上创建索引,因为在连接order_items
表时会用到,加快连接速度。
- 在
order_items
表的order_id
和product_id
列上创建联合索引,这样在连接orders
表和products
表时都能提高效率。
- 在
products
表的product_id
列上创建索引,用于连接order_items
表。
- 查询优化:
- 避免使用
SELECT *
,只选择需要的字段,减少数据传输和处理量。
- 分析查询计划(如使用
EXPLAIN
关键字),查看查询执行的实际情况,根据结果调整索引和查询结构。
- 数据分区:
- 如果数据量非常大,可以考虑对
orders
表和order_items
表按order_date
进行分区,比如按月份或年份分区。这样在查询特定时间段的订单时,可以快速定位到相关的数据分区,减少扫描的数据量。