Hi Clive
Sorry, but I added some comments in the other forum that you may find of interest.
Your use of "OR" I think has destroyed the meaning of your query, as "AND" usually takes precedence so your query is in fact (note the additional brackets):
SELECT Categories.CategoryID, Sum(InvoiceDetails.Amount) AS tot
FROM Categories, InvoiceDetails, Invoices
WHERE (Categories.CategoryID = InvoiceDetails.CategoryID
AND Invoices.InvoiceID = InvoiceDetails.InvoiceID
AND Invoices.ReturnID = '4090604' )
OR (Categories.Categoryid Is Null
AND Categories.ResaleOhdTakings = 'R')
GROUP BY Categories.CategoryID
Ignoring the first set of brackets and concentrating on the second, you will note that there are no binding conditions between the tables. This would mean that every record in CATEGORIES (20 entries) would be matched aginst every record in INVOICEDETAILS (3000) and in turn against every record in INVOICES (say, 50 - I think that this would probably be higher, but bear with me). So you now have a table containing 20 * 3000 * 50 = 3 million records!!! This is why your query is slow.
The use of "OR Categories.Categoryid Is Null" is puzzling unless you are trying to include categories without an invoice in which case I would delete the line and replace your FROM statement with:
FROM categories
LEFT INNER JOIN InvoiceDetails ON Categories.CategoryID = InvoiceDetails.CategoryID
LEFT INNER JOIN Invoices ON Invoices.InvoiceID = InvoiceDetails.InvoiceID
This will include all categories irrespective of whether there are any corresponding records in InvoiceDetails or Invoices.
You could also try applying unique indexes to all ???ID type fields in your database.
Best wishes
Marcus.
--
All suggestions given are just that, we accept no liability for or guarantee any
suggestions made. Any changes to your system or business decisions are taken entirely at your own risk.
|