从5个表插入到表联接中,保持外键约束

时间:2018-07-15 13:08:26

标签: sql

Table structure

我正在尝试使用5个不同表中的信息插入表中,但是我无法看到正确的必需信息,或者有重复项,或者只有在满足所有条件(如果一个表为null且另一个表为其他)时才插入作为相应的值,我的表具有外键,具体取决于之前的查询在下面

INSERT INTO [IVB].[dbo].[ivb_tasks]
            (taskname,
             subclassificationid,
             uniformateleveloneid,
             uniformateleveltwoid,
             uniformatelevelthreeid,
             groupid,
             custom)
SELECT t.discription,
       subcls.subclassificationid,
       l1.uniformateleveloneid,
       l2.uniformateleveltwoid,
       l3.uniformatelevelthreeid,
       g.groupid,
       t.custom
FROM   [IVB].[dbo].[tasks$] t
       INNER JOIN [IVB].[dbo].[ivb_classification] cls
               ON t.classification = cls.classification
       INNER JOIN [IVB].[dbo].[ivb_subclassification] subcls
               ON t.[sub classification] = subcls.subclassification
       INNER JOIN [IVB].[dbo].[ivb_group] g
               ON t.[group name] = g.groupname
       LEFT JOIN [IVB].[dbo].[ivb_level_1] l1
              ON t.[level 1] = l1.uniformatelevelone
       LEFT JOIN [IVB].[dbo].[ivb_level_2] l2
              ON t.[level 2] = l2.uniformateleveltwo
       LEFT JOIN [IVB].[dbo].[ivb_level_3] l3
              ON t.[level 3] = l3.uniformatelevelthree
WHERE  cls.classificationid = subcls.classificationid
       AND subcls.subclassificationid = l1.subclassificationid
       AND l1.uniformateleveloneid = l2.uniformateleveloneid
       AND l2.uniformateleveltwoid = l3.uniformateleveltwoid
GROUP  BY t.discription,
          subcls.subclassificationid,
          l1.uniformateleveloneid,
          l2.uniformateleveltwoid,
          l3.uniformatelevelthreeid,
          g.groupid,
          t.custom
ORDER  BY t.discription  

0 个答案:

没有答案