简体   繁体   中英

How can I improve this inner join query?

My database has 3 tables. One is called Customer, one is called Orders, and one is called RMA. The RMA table has the info regarding returns. I'll include a screen shot of all 3 so you can see the appropriate attributes. This is the code of the query I'm working on:

SELECT State, SKU, count(*) from Orders INNER JOIN Customer ON Orders.Customer_ID = Customer.CustomerID INNER JOIN RMA ON Orders.Order_ID = RMA.Reason Group by SKU Order by SKU LIMIT 10;

I'm trying to get how much of each product(SKU) is returned in each state(State). Any help would really be appreciated. I'm not sure why, but anytime I include a JOIN statement, my query takes anywhere from 5 minutes to 20 minutes to process.

订单表 [ Customer table]

! 2 [ RMA table]

! 3

Your query should look like this:

SELECT c.State, o.SKU, COUNT(*)
FROM Orders o INNER JOIN
     Customer c
     ON o.Customer_ID = c.CustomerID JOIN
     RMA
     ON o.Order_ID = RMA.Order_Id
GROUP BY c.State, o.SKU
ORDER BY SKU;

Your issue is probably the incorrect JOIN condition between Orders and RMA .

If you have primary keys properly declared on the tables, then this query should have good-enough performance.

Given you are joining with an Orders table I'm going to assume this table contains all the orders that the company has ever done. This can be quite large and would likely cause the slowness you are seeing.

You can likely improve this query if you place some constraint on the Orders you are selecting, restricting what date range you use is common way to do this. If you provide more information about what the query is for and how large the dataset is everyone will be able to provide better guidance as to what filters would work best.

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