我正在尝试编写一个查询,该查询将提取分配给它们的相同选项值的产品。受影响的表是:
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.)
每个产品在“rel_product_options”表中都有多个选项值组合。同一产品的变体不能具有相同的选项值对,这就是为什么在更改任何选项的任何值之前,我需要检查下一个值是否与其他产品没有冲突。让我们假设
- 产品A(颜色:红色,尺寸:10)
- 产品B(颜色:蓝色,尺寸:10)
现在,如果我尝试将“产品 B”的颜色更改为“红色” - 我应该能够在数据库中找到“产品 A”的选项相同并取消更改。我希望这个问题很清楚,老实说,我什至不知道从哪里开始:无论我使用多少次,sql 对我来说都是一个谜……我从下面的代码开始,但我认为这可能是错误的,比我能指望的更多,所以非常感谢任何帮助。
# 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 ...