I'm looking for an alternative SQL query to the following statement:
SELECT COUNT(`id`) FROM `products`
WHERE
`category` = "Motors" AND
`id` IN(SELECT `id` FROM `products` WHERE
`Horsepower` > 200 AND
`id` IN(SELECT `id` FROM `products` WHERE
`Manufacturer` = "Baldor"))
As you can see, theoretically (because I didn't specifically test it) the sub queries all select product IDs. Then, a COUNT is generated from the final list of product IDs. This method can get slow when many nested queries are there.
I'm working on a filtering system. So one or more filters and sub filters are selected and a COUNT is generated based on the current selection.
It will be fantastic if I can create a SQL statement to return the number of products based on any number of sub filters (without creating "WHERE IN" clauses).
The above query can be simply made to use only the WHERE...AND clause. The problem lies in using something like the following as sub queries because it needs to select multiple conditions:
SELECT `products`.`id` FROM `products`
LEFT JOIN `attributes` ON `attributes`.`product_id` = `products`.`id`
WHERE `attributes`.`Label` = "Horsepower" AND
`attributes`.`Value` > 200
SELECT `products`.`id` FROM `products`
LEFT JOIN `attributes` ON `attributes`.`product_id` = `products`.`id`
WHERE `attributes`.`Label` = "Category" AND
`attributes`.`Value` = "Motors"
where category=motors and horsepower > 200 and manufacturer = balor
?)
s.