SQL更新由同一个表加入另一个表

时间:2016-02-26 04:59:46

标签: sql sql-server join sql-update

我在SQL Server中有一个Location表:

   LocationId | LocationName |   Address
   ========================================
       15            AA         111 AAA
       17            CC         999 CCC

我有WorksiteWorksiteMark = Null

  WorksiteId | WorksiteName |   Address   |  LocationId | WorksiteMark
   ======================================================================
       1            AA           111 AAA         15            Null
       2            P            23  P           15            Null
       3            F            78  F           15            Null
       4            H            16  H           17            Null
       5            CC           999 CCC         17            Null
       6            W            78  W           17            Null

最后,我需要使用WorksiteMark = WorksiteId表更新Location引用,我将删除Location

   WorksiteId | WorksiteName |   Address   | WorksiteMark
   ========================================================
       1            AA           111 AAA           1
       2            P            23  P             1
       3            F            78  F             1
       4            H            16  H             5
       5            CC           999 CCC           5
       6            W            78  W             5

您能否帮我创建一个脚本来更新引用WorksiteMark = WorksiteId表的Location

由于

3 个答案:

答案 0 :(得分:0)

您的更新需要加倍JOIN,例如;

UPDATE W 
SET W.WorksiteMark = W2.WorksiteId
FROM Worksite AS W
INNER JOIN Location AS L 
       ON L.LocationId = W.LocationId
INNER JOIN Worksite AS W2
       ON W2.WorksiteName = L.LocationName

答案 1 :(得分:0)

希望这适合你。

Update W
SET W.WorksiteMark = L1.WorksiteId
FROM #Worksite AS W
INNER JOIN (Select L.LocationId,W2.WorksiteId FROM #Location L INNER JOIN 
            #Worksite W2 ON L.LocationName = W2.WorkSiteName) AS L1
     ON W.LocationId = l1.LocationId

答案 2 :(得分:0)

UPDATE [dbo].[Worksite]
SET WorksiteMark = (SELECT WorksiteId FROM [dbo].[Worksite] B WHERE B.WorksiteNAME = [dbo].[Location].LocationName)
from [dbo].[Worksite]
inner join [dbo].[Location] on [dbo].[Location].[LocationId] = [dbo].[Worksite].LocationId