[英]How to update table using 2 joins?
我有一個eshop數據庫,並且已經復制了一些產品,以便將它們移到其他類別( wholesale/retail
)。 我需要更新名稱中帶有'[CLONE]'
每個產品的category_id
,這就是我正在做的事情:
首先,我檢查需要移動多少產品:
select p.product_id, pd.product, pc.category_id
from cscart_products p
join `cscart_product_descriptions` pd on p.product_id = pd.product_id
join `cscart_products_categories` pc on p.product_id = pc.product_id
where pd.product like '%CLONE%'
and pc.category_id = '17'; -- 17 is the current category_id
提取了16行;
然后,我執行更新:
UPDATE cscart_products_categories pc
join `cscart_product_descriptions` pd on pc.product_id = pd.product_id
join `cscart_products` p on pc.product_id = p.product_id
SET pc.category_id = '30' -- the category to be moved to
WHERE pc.category_id = '17'
AND pd.product like '%[CLONE]%';
9行受影響;
如您所見,只有16個中的9個正在更新,顯然我的更新語句中有問題,但是什么呢?
您的第一個查詢將找到16個具有category_id
= 17的行。
您的第二個查詢將HAD category_id 30 to now have
9行更改category_id 30 to now have
category_id 17。
因此,在第二個查詢之后,重新運行第一個查詢應發現帶有category_id 17的16 + 9 = 25條記錄。
如果要發現將更新多少結果,則應使用`category_id = 30運行第一個查詢:
select p.product_id, pd.product, pc.category_id
from cscart_products p
join `cscart_product_descriptions` pd on p.product_id = pd.product_id
join `cscart_products_categories` pc on p.product_id = pc.product_id
where pd.product like '%CLONE%'
and pc.category_id = '30'; -- the one that will be changed
-找到9行
UPDATE cscart_products_categories pc
join `cscart_product_descriptions` pd on pc.product_id = pd.product_id
join `cscart_products` p on pc.product_id = p.product_id
SET pc.category_id = '17'
WHERE pc.category_id = '30' -- the category to be moved to
AND pd.product like '%[CLONE]%';
-9行受影響
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.