使用连接的SQL更新查询

我必须更新一个由3个表连接返回的值的字段。

例:

select im.itemid ,im.sku as iSku ,gm.SKU as GSKU ,mm.ManufacturerId as ManuId ,mm.ManufacturerName ,im.mf_item_number ,mm.ManufacturerID from item_master im, group_master gm, Manufacturer_Master mm where im.mf_item_number like 'STA%' and im.sku=gm.sku and gm.ManufacturerID = mm.ManufacturerID and gm.manufacturerID=34 

我想更新表item_mastermf_item_number字段值与在上述条件下加入的其他值。

我如何在MS SQL Server中执行此操作?

 UPDATE im SET mf_item_number = gm.SKU --etc FROM item_master im JOIN group_master gm ON im.sku = gm.sku JOIN Manufacturer_Master mm ON gm.ManufacturerID = mm.ManufacturerID WHERE im.mf_item_number like 'STA%' AND gm.manufacturerID = 34 

为了清楚起见… UPDATE子句可以引用FROM子句中指定的表别名。 所以im在这种情况下是有效的

通用示例

 UPDATE A SET foo = B.bar FROM TableA A JOIN TableB B ON A.col1 = B.colx WHERE ... 

最简单的方法之一是使用公用表表达式(因为你已经在SQL 2005上):

 with cte as ( select im.itemid ,im.sku as iSku ,gm.SKU as GSKU ,mm.ManufacturerId as ManuId ,mm.ManufacturerName ,im.mf_item_number ,mm.ManufacturerID , <your other field> from item_master im, group_master gm, Manufacturer_Master mm where im.mf_item_number like 'STA%' and im.sku=gm.sku and gm.ManufacturerID = mm.ManufacturerID and gm.manufacturerID=34) update cte set mf_item_number = <your other field> 

查询执行引擎将自行找出如何更新记录。

适应这个到MySQL – 在UPDATE没有FROM子句,但是这个工作:

 UPDATE item_master im JOIN group_master gm ON im.sku=gm.sku JOIN Manufacturer_Master mm ON gm.ManufacturerID=mm.ManufacturerID SET im.mf_item_number = gm.SKU --etc WHERE im.mf_item_number like 'STA%' AND gm.manufacturerID=34 

您可以在UPDATE语句中指定用于确定如何更新和使用“FROM”子句进行更新的附加表,如下所示:

 update item_master set mf_item_number = (some value) from group_master as gm join Manufacturar_Master as mm ON ........ where .... (your conditions here) 

在WHERE子句中,您需要提供条件和联接操作来将这些表绑定在一起。

渣子

没有使用你的SQL以上,但这是一个基于联合声明更新表的例子。

 UPDATE p SET p.category = c.category FROM products p INNER JOIN prodductcatagories pg ON p.productid = pg.productid INNER JOIN categories c ON pg.categoryid = c.cateogryid WHERE c.categories LIKE 'whole%' 
 MySQL: In general, make necessary changes par your requirement: UPDATE shopping_cart sc LEFT JOIN package pc ON sc. package_id = pc.id SET sc. amount = pc.amount 

像这样尝试…

 Update t1.Column1 = value from tbltemp as t1 inner join tblUser as t2 on t2.ID = t1.UserID where t1.[column1]=value and t2.[Column1] = value;