Mysql 如何使用2个联接更新表?

Mysql 如何使用2个联接更新表?,mysql,join,Mysql,Join,我有一个eshop数据库,我复制了一些产品,以便将它们转移到不同的类别(批发/零售)。我需要更新名称中包含'[CLONE]的每个产品的类别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 `cscar

我有一个eshop数据库,我复制了一些产品,以便将它们转移到不同的类别(
批发/零售
)。我需要更新名称中包含
'[CLONE]
的每个产品的
类别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行正在更新,显然我的update语句中出现了问题,但是什么呢?

您的第一个查询找到了16行,其中包含
category\u id
=17

您的第二个查询将具有
category\u id 30的9行更改为现在具有
category\u id 17

因此,在第二次查询之后,重新运行第一次查询应该会发现16+9=25条带有'category_id 17'的记录

如果要发现将更新多少个结果,应使用“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行受影响

我错了,我按错误的顺序发布了值。应该是17,30,而不是30,17。请再次检查我的原始帖子,结果是正确的,我的示例是错误的。我更新了原始帖子,因为我错误地将更新查询中的值按错误的顺序放置。这7个未经证实的值可能已经是30,因此不受影响?