我有相關的產品表是這樣的:的MySQL相關的項目查詢
product_id | related_product_id
1 | 2
1 | 3
1 | 4
2 | 1
3 | 1
4 | 1
而是我想插入新的相關產品ID,使他們所有的比賽。 I.E.如果產品1有2,3,4我不想那些產品2,3,4也有相同的相關ID缺失。
不知道它是如何調用的,但這是可能的嗎?非常感謝。
我有相關的產品表是這樣的:的MySQL相關的項目查詢
product_id | related_product_id
1 | 2
1 | 3
1 | 4
2 | 1
3 | 1
4 | 1
而是我想插入新的相關產品ID,使他們所有的比賽。 I.E.如果產品1有2,3,4我不想那些產品2,3,4也有相同的相關ID缺失。
不知道它是如何調用的,但這是可能的嗎?非常感謝。
您可以使用SELECT
查詢作爲數據源在INSERT
INSERT INTO related_products (product_id, related_product_id)
SELECT r1.product_id, r2.related_product_id
FROM related_products AS r1
CROSS JOIN related_products AS r2
WHERE r1.product_id != 1
AND r2.product_id = 1
此連接將得到所有的產品1的相關產品,並與所有其他產品ID將它們結合起來。
我會建議用戶雙向條件,以獲得相互關聯的產品。例如,如果您對單列product_id應用條件,則不會得到反之亦然的結果。但是,如果你在兩列上檢查這個條件,你會得到結果。
例如:
select related_product_id, product_id from products where related_product_id=1 OR product_id=1
這會給你的相關產品的ID在任一related_product_id或PRODUCT_ID。
同樣,你可以得到它的產品2即
select related_product_id, product_id from products where related_product_id=2 OR product_id=2
這會給所有相關的產品ID在任一related_product_id或PRODUCT_ID。
謝謝。這更復雜,但它完美地完成了這項工作。 – JoeDoe