I’m trying to write a query that would extract products that have identical option values assigned to them. Affected tables are:
products
| id |
rel_product_options
| product | option | value |
"option" is an id from "options" table
"value" is an option value id from "values" table (an option can have multiple values. eg. option "color" can have "red", "blue" etc.)
Every product has multiple option-value combinations ir “rel_product_options” table. Variations of the same product cannot have identical option-value pairs and that’s why prior to changing any value on any option i need to check if the next value would no conflict with some other product. Let’s assume
- product A (color: red, size: 10)
- product B (color: blue, size: 10)
Now if i try to change color of “product B” to “red” – i should be able to find in the database that options of “product A” would be identical and cancel the change. I hope the question is clear and honestly i don’t even know where to start: sql is something of a mystery to me no matter how many times i use it … I’ve started with something like the code below, but i think it is probably wrong on more levels than i can count to so any help is very appreciated.
# my thoughts
SELECT P1.*, PO1.*, PO2.* FROM products AS P1
# first select the product we want to extract all options from
# THIS ALREADY IS WRONG, because one of the options is ABOUT TO CHANGE, but this code assumes it has already done that
JOIN rel_product_options AS PO1 ON (PO1.product = P1.id AND PO1.product = 1)
# now join all other products that do not have identical option-value pairs
LEFT JOIN rel_product_options AS PO2 ON (PO1.product != PO2.product AND PO1.`option` = PO2.`option` AND PO1.value = PO2.value)
# and ... i'm lost ...
Untested, but try something like this to find duplicate products of THIS_PRODUCT_ID. Note I am assuming that each row in
rel_product_optionsis unique.Edit: It looks like you are trying to put this in an
ON UPDATEtrigger forrel_product_options. This is a bit of a hack, but I suppose you could try something like the following. This is of course assuming thatOLD.product = NEW.productotherwise all bets are off:Edit 2: If you’re running this from PHP, changing a parameter’s value, you can try the following. This now assumes that (
product,option) is unique, and the option already exists, with a different value. That is, you will be following up the query with anUPDATEto modify a row, not anINSERT.There are three parameters in this query:
@product: The product ID in question@option: The option you are changing@newValue: The new value you will change the option to