如何仅在查询中追加新记录?

时间:2018-01-05 15:07:20

标签: sql ms-access

我试图创建一个追加查询,看起来我的语法错了。 当我运行追加查询时,我不希望再次追加旧记录,而只是新记录。我将包含我的SQL语句。这也是在访问中运行。

INSERT INTO Table1 ( District, Location, PricePerTon )
    SELECT TestFormWithDeficiency1.District, 
        TestFormWithDeficiency1.Location, 
        TestFormWithDeficiency1.PricePerTon
    FROM TestFormWithDeficiency1
        WHERE (((TestFormWithDeficiency1.RecordCopy)=Yes))
        Where Not Exist (
            Select Location 
            Form Table1 
            Where Table1.Location=TestFormWithDeficiency1.Location);

2 个答案:

答案 0 :(得分:1)

如果where子句中存在多个条件,请使用AND而不是第二个where

INSERT INTO Table1 ( District, Location, PricePerTon )
SELECT TestFormWithDeficiency1.District, 
       TestFormWithDeficiency1.Location, 
       TestFormWithDeficiency1.PricePerTon
FROM TestFormWithDeficiency1
WHERE TestFormWithDeficiency1.RecordCopy=Yes
AND NOT EXISTS (Select Location -- AND instead of second WHERE
                FROM Table1  -- FROM instead of FORM
                WHERE Table1.Location=TestFormWithDeficiency1.Location);

答案 1 :(得分:0)

而不是使用EXISTS加入表,以便返回TestFormWithDeficiency1中的所有记录,只返回Table1中的匹配记录。然后,您可以检查哪个Table1.Location为空。

INSERT INTO Table1 ( District, Location, PricePerTon )
SELECT      TestFormWithDeficiency1.District
            , TestFormWithDeficiency1.Location
            , TestFormWithDeficiency1.PricePerTon
FROM        TestFormWithDeficiency1 LEFT JOIN Table1 ON TestFormWithDeficiency1.Location = Table1.Location
WHERE       RecordCopy=Yes AND Table1.Location IS NULL  

注意:WHERE子句中,我没有为RecordCopy指定表格。这假定Table1中不存在该字段。因为它只出现在一个表中,所以不需要使用表名完全限定。

在大型表上,这应该比使用子查询运行得快一点(或者是相关查询?)