我有MySQL表
ColorOptions
+-----------+---------+------+--------+
| productId | colorId | cost | sorter |
+-----------+---------+------+--------+
| 1 | 1 | 10 | 1 |
| 1 | 3 | 0 | 2 |
| 1 | 33 | .04 | 5 |
| 2 | 3 | 10 | 1 |
| 2 | 4 | 0 | 2 |
+-----------+---------+------+--------+
Product2ategory
+-----------+------------+
| productId | categoryId |
+-----------+------------+
| 1 | 1 |
| 1 | 3 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
+-----------+------------+
我的目标是复制特定产品的所有colorOptions,并将其应用于该类别中的所有其他产品(替换现有选项)。所以productId 2& 3(但不是4)将在ColorOptions表中具有与productId 1相同的所有行。例如
DELETE FROM `ColorOptions` WHERE `productId` IN (SELECT `productId` FROM `Product2Category WHERE `categoryId` = 1 AND `productId` != 1)
删除当前条目,以便可以使用以下内容进行更新:
INSERT INTO `ColorOptions` (`productId`,`colorId`,`cost`,`sorter`)
SELECT (SELECT `productId` FROM `Product2Category WHERE `categoryId` = 1 AND `productId` != 1) as 'product',`colorId`,`cost`,`sorter` FROM `ColorOptions` WHERE `productId` = 1
我知道由于子查询确实有效,但这是我能解释我要找的东西的最好方法。我一直在尝试一堆JOIN,但没有运气。
这是理想的结果:
+-----------+---------+------+--------+
| productId | colorId | cost | sorter |
+-----------+---------+------+--------+
| 1 | 1 | 10 | 1 |
| 1 | 3 | 0 | 2 |
| 1 | 33 | .04 | 5 |
| 2 | 1 | 10 | 1 |
| 2 | 3 | 0 | 2 |
| 2 | 33 | .04 | 5 |
| 3 | 1 | 10 | 1 |
| 3 | 3 | 0 | 2 |
| 3 | 33 | .04 | 5 |
+-----------+---------+------+--------+