使用联接中的数据更新相关表中的列

时间:2014-08-12 22:25:34

标签: sql-server tsql

我有三张表格,其中包含医生及其所属的实践和医疗保健组织的数据。例如..

[Table Hmo]
╔════╦════════════════════════════════════╗
║ Id ║                Name                ║
╠════╬════════════════════════════════════╣
║  1 ║ Purple Cross and Yellow Shield HMO ║
║  2 ║ Tifts Health HMO                   ║
╚════╩════════════════════════════════════╝

[Table Practices]
╔════╦═══════╦═════════════════════════╗
║ Id ║ HmoId ║          Name           ║
╠════╬═══════╬═════════════════════════╣
║  1 ║     1 ║ Downtown Cardiac Group  ║
║  2 ║     1 ║ Tropical Medicine Group ║
║  3 ║     2 ║ Action SportsMed Group  ║
╚════╩═══════╩═════════════════════════╝

[Table Physicians]
╔════╦═══════╦════════════╦══════════════════╗
║ Id ║ HmoId ║ PracticeId ║       Name       ║
╠════╬═══════╬════════════╬══════════════════╣
║  1 ║ ?     ║          1 ║ Dr. Trapper-John ║
║  2 ║ ?     ║          1 ║ Dr. Doolittle    ║
║  3 ║ ?     ║          2 ║ Dr. Smith        ║
║  4 ║ ?     ║          3 ║ Dr. Flintstone   ║
╚════╩═══════╩════════════╩══════════════════╝

我知道HmoId列不是必需的,因为表是通过外键链接的,但是,用户仍然希望填充此列。我无法弄清楚如何使用更新查询填充HmoId列。

我可以编写一个查询来获取每个医生的HmoId ...

SELECT Physicians.Name, Hmo.Name
FROM Physicians 
    LEFT JOIN Practices ON Physicians.PracticeId = Practices.Id
    LEFT JOIN Hmo ON Practices.HmoId = Hmo.Id

但是如何将其转换为更新查询却让我感到不舒服。

1 个答案:

答案 0 :(得分:3)

Update p set 
p.hmoid = h.id 
FROM Physicians p
    LEFT JOIN Practices pr ON pr.id = p.practiceid
    LEFT JOIN Hmo h ON h.id = pr.HmoId