0

I'm using the following query:

SELECT tProducts.intProductId, tProducts.strSKU, tProducts.strProductName, (SELECT count(*) FROM tProducts as tProductOptions WHERE tProductOptions.bolDeleted = 0 AND tProductOptions.intOptionId = tProducts.intProductId) FROM tProducts WHERE bolDeleted = 0 AND intOptionId = 0 

The table has intProductId as an integer, strSKU & strProductName as varchar and intProductId as an integer that relates back to intProductId if the row represents an option of the product. (This isn't my schema!)

I'm trying to get each of the products and the number of options.

It works and gives the results I expect, but it's slow when there is a lot of data.

I have added relevant indexes, but I'm sure there must be a better way of doing this... I just can't see it!

(Additionally, I'm trying to put this query into Laravel Fluent - but the best option seems to be raw. Am I missing something here too?) Thanks

2
  • would you post the table structure and what you want to retrieve as result Commented Nov 29, 2013 at 12:07
  • Additional information added - thanks. Commented Nov 29, 2013 at 13:28

1 Answer 1

1

Try to rewrite the query using JOIN instead of dependent subquery.
It might be faster a bit (but there is no guarantee).

SELECT t.intProductId, t.strSKU, t.strProductName, q.cnt FROM tProducts t LEFT JOIN ( SELECT intOptionId, count(*) cnt FROM tProducts as tProductOptions WHERE tProductOptions.bolDeleted = 0 GROUP BY intOptionId ) q ON t.intProductId = q.intOptionId WHERE t.bolDeleted = 0 AND t.intOptionId = 0 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks kordirko - but I'm afraid it's not quicker. When I tested, my query was 0.862 seconds for 43847 vs yours at 1.012 seconds on the same data. But, I hadn't thought of doing it that way, so thanks...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.