使用第三个表从另一个表中插入表中的行

时间:2015-05-13 08:10:22

标签: sql sql-server database stored-procedures join

我的数据库中有3个表,如下所示: enter image description here

我想在RESULT表的Infos表中插入数据。并且只插入Picker表中列出的那些行。但由于InfoID表的Result列是主键,因此它会限制已存在的InfoID再次重新插入。 Picker表' InfoID'可以有重复的价值观。 Picker表实际上是在存储过程中创建的临时表。

我不太专业地进行加入查询,因此我接受了一些SO问题的帮助并开发了以下查询:

INSERT INTO @Result([INFOID],[VALUE],[PROCESSED]) (SELECT T1.Id,
      CASE 
         WHEN T1.Value1 = '-1' THEN T1.Value2
         ELSE T1.Value1
      END, 0 
    FROM [Infos] T1 LEFT JOIN (SELECT [InfoIDs] FROM Picker AS A1 WHERE (NOT EXISTS (SELECT [INFOID] FROM @Result AS A2 WHERE A1.[InfoIDs] != A2.[INFOID]))) T2 ON T1.Id = T2.InfoIDs)

但问题是我在Result表的输出中只得到一行。请告诉我我的查询有什么问题?

更新

预期结果:

enter image description here

4 个答案:

答案 0 :(得分:1)

我没有测试过这个,但它应该可行。首先,您从Infos获取不同的值,然后将它们合并到结果表中。如果InfoID已存在于result中,则更新该值。如果它不存在则添加它。如果您不想更新现有记录并仅添加新记录,请移除WHEN MATCHED THEN UPDATE块,最多但不包括WHEN NOT MATCHED THEN UPDATE

MERGE INTO 
    Result
USING
    (SELECT
        DistinctInfos.ID,
        CASE WHEN DistinctInfos.Value1= -1 THEN DistinctInfos.Value2 ELSE DistinctInfos.Value1 END ValueToInsert
    FROM
        (SELECT
            Infos.ID,
            MAX(Infos.Value1) Value1,
            MAX(Infos.Value2) Value2
        FROM
            Infos
            INNER JOIN Picker ON Infos.ID = Picker.InfoIDs
        GROUP BY 
            Infos.ID
        ) DistinctInfos
    )InfosToBeInserted
ON
    (Result.InfoID = InfosToBeInserted.ID)
WHEN MATCHED THEN UPDATE
    SET Result.Value = InfosToBeInserted.ValueToInsert
WHEN NOT MATCHED THEN INSERT
    (
        InfoID,
        Result,
        Processed
    )
    VALUES
    (
        InfosToBeInserted.ID,
        InfosToBeInserted.ValueToInsert,
        0
    )

答案 1 :(得分:1)

我们可以这样做:

INSERT INTO @Result(InfoID, Value, Processed)
(
    SELECT DISTINCT
        inf.Id,
        CASE WHEN inf.Value1 = '-1' THEN inf.Value2 ELSE inf.Value1 END,
        0 
    FROM Infos inf
    INNER JOIN Picker pic ON inf.Id = pic.InfoIDs
    WHERE NOT EXISTS (SELECT 1 FROM @Result res WHERE res.InfoID = pic.InfoIDs)
)

答案 2 :(得分:1)

我认为你需要这个查询:

INSERT INTO @Result
(SELECT ID, 
    CASE 
         WHEN i.Value1 = '-1' THEN i.Value2
         ELSE i.Value1
      END
Value1, 0
FROM Infos i
WHERE i.ID In (SELECT InfoIDs FROM Picker)
  AND NOT i.ID IN (SELECT InfoID FROM @Result))

答案 3 :(得分:1)

最后,我弄清楚究竟出了什么问题:

INSERT INTO @Result([INFOID],[VALUE],[PROCESSED]) (SELECT T1.Id,
      CASE 
         WHEN T1.Value1 = '-1' THEN T1.Value2
         ELSE T1.Value1
      END, 0 
    FROM [Infos] T1 INNER JOIN (SELECT [InfoIDs] FROM Picker AS A1 WHERE (NOT EXISTS (SELECT [INFOID] FROM @Result AS A2 WHERE A1.[InfoIDs] = A2.[INFOID]))) T2 ON T1.Id = T2.InfoIDs)

我使用INNER JOIN并且在A1.[InfoIDs != A2.[INFOID]条件下我添加了=而不是!=

我结合了这个问题的响应者提出的所有解决方案和提示,并提出了这个解决方案。谢谢大家。 :)