I have a table structure as follows and I want to select
all active categories
with active products
of a particular parent ID.
So if I plug in a particular parentID, I only get relevant active subcategories of the parent that contains active products.
This is my sql (mysql) so far which works, but looks pretty nasty, and for the sake of academia I want to know if there’s a better way. It would seem to me that selecting all of the productIDs that are active to filter the results is kind of a waste, but I can’t figure a way around this, or does mysql figure out the best way to process this query?
(many-to-many upon itself)
categories
----------
categoryID
parentID
name
isActive (bool)
(linker table between categories and product)
productCategories
-----------------
productID
categoryID
products
--------
productID
name
isActive (bool)
SELECT productCategories.categoryID, categories.* FROM productCategories
LEFT JOIN categories ON
productCategories.categoryID = categories.categoryID
WHERE
productCategories.categoryID IN
(SELECT categoryID FROM categories WHERE parentID = {$parentID} AND isActive = 1)
AND
productCategories.productID IN
(SELECT productID FROM products WHERE isActive = 1)
GROUP BY productCategories.categoryID
An alternative layout could be as follows…