Mysql在Query中加入查询优化

问题描述 投票:0回答:2

尝试调试缓慢的查询:

SELECT IFNULL(SUM(bt.transactionQuantity * bpd.unitPrice), 0)
FROM batchTransaction bt
LEFT JOIN batch b ON b.id = bt.batchId
LEFT JOIN batchPricingDetails bpd ON bpd.id = b.batchPricingDetailsId
WHERE (bt.productId, bt.dateCreated) IN (
    SELECT productId, MAX(dateCreated)
    FROM batchTransaction
    WHERE organisationId = '714361434540086498'
    AND dateCreated < 1689877800000
    GROUP BY productId
);

不是在查询中使用尝试进行连接,而是给出错误结果,其幅度大于 10 倍。

SELECT IFNULL(SUM(bt.transactionQuantity * bpd.unitPrice), 0)
FROM batchTransaction bt
JOIN (
    SELECT bt.productId, max(bt.dateCreated)
    FROM batchTransaction bt
    WHERE bt.organisationId = '714361434540086498' AND bt.dateCreated < 1689877800000
    GROUP BY bt.productId
) AS filtered_data ON bt.productId = filtered_data.productId
LEFT JOIN batch b ON b.id = bt.batchId
LEFT JOIN batchPricingDetails bpd ON bpd.id = b.batchPricingDetailsId;
mysql performance query-optimization
2个回答
0
投票

您缺少

ON
子句中的日期比较。

SELECT IFNULL(SUM(bt.transactionQuantity * bpd.unitPrice), 0)
FROM batchTransaction bt
JOIN (
    SELECT bt.productId, max(bt.dateCreated) AS maxDate
    FROM batchTransaction bt
    WHERE bt.organisationId = '714361434540086498' AND bt.dateCreated < 1689877800000
    GROUP BY bt.productId
) AS filtered_data ON bt.productId = filtered_data.productId AND bt.dateCreated = filtered_data.maxDate
LEFT JOIN batch b ON b.id = bt.batchId
LEFT JOIN batchPricingDetails bpd ON bpd.id = b.batchPricingDetailsId;

0
投票
  • 根据您的 MySQL 的年龄,此结构可能非常优化不佳;避免它:

    WHERE (a,b) IN ...
    
  • 另外,尝试将其更改为

    JOIN
    EXISTS
    (就像您在第二个查询中所做的那样):

    ... IN ( SELECT ... )
    
  • 索引:

    batchTransaction:  INDEX(organisationId, productId, dateCreated)
    
  • “给出的错误结果超过 10 倍”——呃?请详细说明。

© www.soinside.com 2019 - 2024. All rights reserved.