I want to optimize the following query to avoid multiple count runs.
SELECT product.Id,
IF((SELECT COUNT(*)
FROM productorders
WHERE productorders.ProductId = product.Id) > 0,
(SELECT COUNT(*) FROM productorders WHERE productorders.ProductId = product.Id),
9999999999
)
FROM product
can someone suggest a solution for the same
I am using more complex logic in the magic number 9999999999 which I have avoided here for simplicity
Also this query is a small chunk of a much larger query...which i am avoiding for simplicity
The explain result is as below
+ Options id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY product index NULL CategoryId 8 NULL 25 Using index
3
DEPENDENT SUBQUERY productorders ref PRIMARY PRIMARY 8 tabletest.product.Id 1 Using index 2
DEPENDENT SUBQUERY productorders ref PRIMARY PRIMARY 8 tabletest.product.Id 1 Using index