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