小编典典

使用联接的SQL更新查询

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

我想用其他在上述条件下加入的mf_item_number值来更新表的字段值item_master

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


阅读 195

收藏
2021-05-05

共1个答案

小编典典

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 ...
2021-05-05