Trying to debug a slow query:
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
);
Instead of using in query trying to do join but it is giving erroneous results by a margin of greater than 10X.
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;
2
Answers
You’re missing the date comparison in the
ON
clause.Depending on how old your MySQL is, this construct may be very poorly optimized; avoid it:
Also, try to change this to a
JOIN
orEXISTS
(as you did in second query):Index:
"giving erroneous results by a margin of greater than 10X" — Eh? More specifics, please.