我有一个半复杂的JOIN
结构,可以根据订单从我的 MySQL 数据库中获取特定信息。首先让我给你 SQL Query;
SELECT
#orders.*,
orders.id,
customers.lastname,
customers.priority,
shipments.status,
pmv_sl.productmodelvariant_id,
pmv_sl.nr AS pmv_nr,
COALESCE(SUM(orderlines.nr), 0) AS orderlines_nr_count,
COALESCE(SUM(shipment_lines.nr), 0) AS shipment_lines_nr_count
FROM orders
INNER JOIN customers ON customers.id = orders.customer_id
INNER JOIN platforms ON platforms.id = orders.platform_id
INNER JOIN stocklocations ON stocklocations.id = platforms.stocklocation_id
LEFT JOIN orderlines ON orderlines.order_id = orders.id
LEFT JOIN shipments ON shipments.order_id = orders.id
LEFT JOIN shipment_lines ON shipment_lines.shipment_id = shipments.id
# This JOIN, together with shipment_lines, makes the query suddenly very slow (probably because of all the SUM()'s)
LEFT JOIN productmodelvariants_stocklocations pmv_sl ON
pmv_sl.productmodelvariant_id = orderlines.productmodelvariant_id
AND pmv_sl.stocklocation_id = stocklocations.id
WHERE
orders.orderstatus_id = 2
AND orders.order_all_to_shipment = 0
GROUP BY
orders.id
问题
所以我计算了这个查询的 4 种速度(所有情况下都有 450 个结果);
- 没有
LEFT JOIN shipment_lines
和没有LEFT JOIN productmodelvariants_stocklocations
LEFT JOIN shipment_lines
只有_LEFT JOIN productmodelvariants_stocklocations
只有_- 两者
2.
兼有3.
这是结果速度;
- 0.146 秒
- 1.975 秒
- 0.234 秒
- 4.619 秒
表格中的行
- 行
orderlines
数:24528 - 行
shipment_lines
数:6345 - 行数
productmodelvariants_stocklocations
:1819
结论
如您所见,一次2.
和3.
(in 4.
) 都参加了比赛;SQL 开始大汗淋漓。
我想知道是否有比我拥有更多(My)SQL 知识的人知道改变查询上下文以提高它的方法。
我还注意到,在执行4.
和引用COALESCE(SUM()
's 时,我很容易获得0.8
秒数1.0
。
更新
解释扩展