I’m having difficulties grasping how to do this. I am making a “product options” table, which will contain all possible variants of a product based on the attributes attached. So if red, small, blue and large are attached to the product the options are small red, large red, small blue and large blue. For this I presume I have to reverse the one-to-many, but I am struggle with how.
Right now I am trying to retrieve an option that matches the specified values. So for example, if I search for red and small, it will give me the “small red” option. This is what I have been trying based on a previous question I asked:
SELECT o.name
FROM shop_products_options o
WHERE o.id IN (
SELECT v.option_id
FROM shop_products_options_values v
WHERE v.product_id = 1 AND v.value_id IN(4,7)
GROUP BY v.option_id
)
This returns all options that match either 4 or 7 (the IDs for the small and red values) just once. How can I get it to return just the option_id’s that are an exact match to both 4 and 7?
I could do it using a comma-delimited list but I’d rather see if there is a normalized way of doing it first that will work.
Thanks for any advice 🙂
Unless I’ve misunderstood, try something like this. Search for all option_id’s for 4, and then for 7 and use INTERSECT to only return the values which exist for both.
Note – INTERSECT isn’t supported in MySQL, so an alternative would be to use multiple subqueries
The GROUP BY part may not be necessary