I need to return a list of product id’s that are…
- Within a specific category (for example ‘Clothing’)
- Which have various attributes, such as ‘Red’ or ‘Green’
- Which are themselves within attribute ‘groups’ such as ‘Color’
I’m getting stuck when I need to select MULTIPLE attribute options within MULTIPLE attribute groups. For example, if I need to return a list of products where Color is ‘blue’ OR ‘red’ AND size is ‘Medium’ OR ‘XXL’.
This is my code:
SELECT `products.id`
FROM
`products` ,
`categories` ,
`attributes` att1,
`attributes` att2
WHERE products.id = categories.productid
AND `categories.id` = 3
AND att1.productid = products.id
AND att1.productid = att2.productid
AND
(att1.attributeid = 58 OR att1.attributeid = 60)
AND
(att2.attributeid = 12 OR att2.attributeid = 9)
I believe this code works, but It looks pretty messy and I’m not sure my ‘dirty’ self-join is the correct way to go. Has anyone got any ideas on a more ‘elegant’ solution to my problem?
Please use the modern join syntax:
It’s easier to read because it clearly demarques join conditions from row filtering conditions. It’s also easier for the SQL optimizer to identify these distinctions and create better query plans
Edited
I alsp added the use of
IN (...). Not only does it look nicer, the DB wil use an index withINbut usually not withOR, even though they mean the same thing