简体   繁体   中英

MySQL LEFT JOIN two nested tables performance

I have query similar to this, this code works, but have performance issues:

SELECT Mat.Name, Inc.Quantity, Outg.Quantity FROM Materials AS Mat
LEFT JOIN ( SELECT MaterialsID, SUM(Quantity) AS Quantity FROM Incoming GROUP BY MaterialsID ) AS Inc
ON Inc.MaterialsID=Mat.ID
LEFT JOIN ( SELECT MaterialsID, SUM(Quantity) AS Quantity FROM Outgoing GROUP BY MaterialsID ) AS Outg
ON Outg.MaterialsID=Mat.ID
ORDER BY Mat.ID ASC
LIMIT 10

No matter if LIMIT (or WHERE clause) selects 1, 10 or 1000 rows, execution time is the same (which in my case is 4 seconds if not cached). Is there good approach to optimize this query while keeping code readable?

What appears to be happening is that you have a pair of sub queries (which are possibly not quick), and then the results are joined against the Materials table before discarding all except the first 10 ids. If there are a large number of records on materials then this is doing a large and slow join (a sub query is not going to pass back an index to be used in the join) before dropping most of the records

While I am normally not keen on them, this is probably a time when you would need to use a sub query in the SELECT( a correlated sub query). This will mean it will only calculate the quantities for the 10 records you care about.

SELECT Mat.Name, 
        ( SELECT SUM(Quantity) FROM Incoming WHERE MaterialsID=Mat.ID ) Inc_Quantity, 
        ( SELECT SUM(Quantity) FROM Outgoing WHERE MaterialsID=Mat.ID ) Out_Quantity
FROM Materials AS Mat
ORDER BY Mat.ID ASC

LIMIT 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM