从另一个(一对多关系)插入TABLE

时间:2017-04-04 17:16:46

标签: sql sql-server tsql one-to-many insert-update

我有一张桌子"乔布斯"它有列(JobID,Time,DrvNo ......)。 我有另一张桌子" JobDetails" (JobFK,PkSequence,IsDestination,PC)。 Jobs和JobDetails之间存在一对多关系。

Data in Jobs is as follows:
Jobs
==================
JobID, Time, DrvNO
==================
1, 12:30, 123
2, 13:50, 343
3, 14:00, 234

Data in JobDetails as follows:
JobDetails
==============================================
JobFK, PkSequence, IsDestination, PC
==============================================
1, 0, 0, AB1
1, 1, 1, DE1
2, 0, 0, RT1
2, 1, 0, DS1
2, 2, 1, KJ1
3, 0, 0, YU7
3, 1, 1, TH1

我想要做的是通过在Jobs中插入两个列来合并这两个表,并尝试通过从JobDetails获取Pickup和Destination来填充Jobs;如下:

Jobs
==================
JobID, Time, DrvNO, Pickup, Dropoff
==================
1, 12:30, 123, AB1, DE1
2, 13:50, 343, RT1, KJ1
3, 14:00, 234, YU7, TH1

我已经实现了SELECT部分​​,如下所示:

SELECT cj.JobID, cj.Time,cj.DrvNo, j.PC AS Pickup, k.PC AS Dropoff
FROM Jobs AS cj
 LEFT JOIN JobDetails AS j ON (cj.JobID = j.JobFK AND j.PKSequence = 0)
 LEFT JOIN JobDetails AS k ON (cj.JobID = k.JobFK AND k.IsDestination= 1)

上面的SELECT工作正常,但如何使用此查询中的数据插入/更新现有表(作业)?

感谢任何帮助。 感谢

1 个答案:

答案 0 :(得分:3)

这里是SQL添加列,然后使用select查询中的值更新它们(因为你说它们正在为你想要的工作而没有验证连接)。您可以根据需要更改新列的类型,只需根据您的给定数据进行猜测。

ALTER TABLE Jobs
    ADD Pickup VARCHAR(3)
        ,Dropoff VARCHAR(3)
;
GO

UPDATE cj
    SET cj.Pickup = j.PC
        ,cj.Dropoff = k.PC
FROM Jobs AS cj
 LEFT JOIN JobDetails AS j ON (cj.JobID = j.JobFK AND j.PKSequence = 0)
 LEFT JOIN JobDetails AS k ON (cj.JobID = k.JobFK AND k.IsDestination= 1)