将表A中的行复制到表B,其中键不存在

时间:2016-12-14 09:49:18

标签: sql ms-access

我有这个问题:

INSERT INTO Master (Case)
SELECT Case
FROM Extract
WHERE (NOT Exists (SELECT 1
                  FROM Extract
                  WHERE Master.Case = Extract.Case))
GROUP BY Case;

我有两个表,Master和Extract,都有Case作为它们的唯一键。

我想将Extract中的所有行复制到Master中不会出现的行,因此任何行中的案例编号都不在Master中。

希望这是有道理的。

当我运行查询时,它表示为Master.Case输入参数值

我做错了什么?

2 个答案:

答案 0 :(得分:1)

尝试在括号[]中使用列名,即[Case]。因为它在SQL的保留字中用于CASE WHEN。

            insert into .Master([Case]) 
            select distinct [Case] from Extract where [Case] NOT IN(select [Case] from Master);

            OR

            insert into Master([Case]) 
            select distinct [Case] from Extract t1 where NOT EXISTS(select [Case] from Master t2 where t1.[Case]=t2.[Case]);

答案 1 :(得分:0)

INSERT INTO [Master] ([Case])
SELECT [Case]
FROM [Extract]
WHERE NOT Exists (SELECT 1 FROM [Extract] WHERE [dbo].[Master].[Case] = [dbo]. 
[Extract].[Case])
GROUP BY [Case]