如何提高带有额外条件的 MySQL 查询的速度?

How to increase the speed of MySQL query with extra condition?

我正在尝试加快以下查询的速度,因为 运行 需要很长时间:现在是 'only' 大约 1.5 秒,但是随着行数的增加肯定会变慢(这将下一个时期的 10 倍)。

基本上,我想为用户显示订单 table 中的所有行,并且每行显示总订单金额(这是 orders_products table).

SELECT 
orders.order_number,
orders.order_date, 
companies.company_name,
COALESCE(SUM(orders_products.product_price * orders_products.product_quantity),0) AS order_value 
FROM orders 
LEFT JOIN companies ON companies.id = orders.company_id
LEFT JOIN orders_products ON orders_products.order_id = orders.id
LEFT JOIN users ON users.id = orders.user_id 
WHERE orders.user_id = '$user_id'
AND companies.user_id = '$user_id'
GROUP BY orders.id ORDER BY orders.order_date DESC, orders.order_number DESC

我试过添加另一个条件 AND orders_products.user_id = '$user_id'。在速度方面,查询速度大约快 12 倍(是的!),但问题是并非所有订单中都有产品。在这种情况下,没有产品的订单不会被退回。

如何更改我的查询,以便尽管订单中没有产品,它仍然会被退回(总订单值为 0),同时还能加快查询速度?

预先感谢您的帮助!

您可能会发现使用相关子查询更快:

SELECT o.order_number, o.order_date,  c.company_name,
      (SELECT COALESCE(SUM(op.product_price * op.product_quantity), 0)
       FROM orders_products op
       WHERE op.order_id = o.id
      ) AS order_value 
FROM orders o LEFT JOIN
     companies c
     ON c.id = o.company_id AND c.user_id = o.user_id
WHERE o.user_id = '$user_id'
ORDER BY o.order_date DESC, o.order_number DESC

这摆脱了通常是性能胜利的外部聚合。

然后为了性能你需要以下索引:

  • orders(user_id, order_date desc, order_number_desc, company_id)
  • companies(id, company_id, company_name)
  • orders_products(order_id, product_price, product_quantity)