面试题答案
一键面试优化思路
- 索引优化:
- 在
orders
表的user_id
和order_date
字段上创建复合索引,这可以加速根据用户ID和订单时间筛选订单的操作。例如CREATE INDEX idx_user_date ON orders(user_id, order_date);
- 在
orders
表的product_id
字段上创建索引,便于快速关联到products
表。CREATE INDEX idx_product_id ON orders(product_id);
- 在
products
表的product_id
字段上创建索引,确保关联查询高效。CREATE INDEX idx_product_pid ON products(product_id);
- 在
- 查询语句优化:
- 采用
JOIN
操作时,确保连接条件明确且高效。 - 减少不必要的字段选择,只选择需要的
product_name
和价格总和计算字段。
- 采用
SQL语句
SELECT p.product_name, SUM(p.price) AS total_price
FROM orders o
JOIN products p ON o.product_id = p.product_id
WHERE o.user_id = :specific_user_id
AND o.order_date BETWEEN :start_date AND :end_date
GROUP BY p.product_name;
在上述SQL语句中,:specific_user_id
、:start_date
和:end_date
为参数化查询的占位符,在实际代码中替换为具体值,这样能提高查询效率并防止SQL注入。