追加查询,跳过重复的条目(重复项不是主键)

时间:2015-07-07 18:53:21

标签: sql excel ms-access ms-access-2010

我在这里有一个追加查询。我希望它从Excel电子表格更新Access中的现有项目表。我希望它忽略重复。每次运行它时,都会弹出关于最终“Projects。[Measure]”的错误。我哪里出错了?

INSERT INTO Projects ([Measure],[Customer Number], Store, [Customer Name], [CustomerAddress], [Measure Received])

SELECT [Measure], [Customer Number], [Store], [Customer Name], [CustomerAddress], [MeasureReceived]

FROM NewProjects

WHERE NOT EXISTS
(
SELECT * FROM NewProjects
WHERE NewProjects.[Measure] = Projects.[Measure]
)
;

2 个答案:

答案 0 :(得分:3)

您的主查询包含此子查询:

SELECT * FROM NewProjects
WHERE NewProjects.[Measure] = Projects.[Measure]

WHERE子句引用 Projects。[Measure] 。但是 Projects 不包含在FROM子句中,因此Access猜测 Projects。[Measure] 必须是参数的名称。

考虑一种不同的方法。首先创建一个SELECT查询,返回“非重复”行。 LEFT JOIN NewProjects 项目并要求右侧 Measure 值为空的行 - 那些是 Projects 中不存在(不匹配)的NewProjects 行:

SELECT
    n.Measure,
    n.[Customer Number],
    n.Store,
    n.[Customer Name],
    n.CustomerAddress,
    n.MeasureReceived
FROM
    NewProjects AS n
    LEFT JOIN Projects AS p
    n.Measure = p.Measure
WHERE p.Measure Is Null;

调查Access“不匹配的查询向导”。它可以指导您完成创建类似查询的过程。但无论您是使用向导还是复制我的示例查询并将其粘贴到SQL视图中,请确认它返回正确(非重复)的行。然后,您需要做的就是将INSERT部分添加到查询的开头:

INSERT INTO Projects ([Measure],[Customer Number], Store, [Customer Name], [CustomerAddress], [Measure Received])

答案 1 :(得分:0)

如果没有看到一些示例数据,很难确定,但这可能会为您提供所需的插入集。

INSERT INTO Projects ([Measure],[Customer Number], [Store], [Customer Name], [CustomerAddress], [Measure Received])
    SELECT np.[Sales Document], np.[Sold-to party], np.[Site], np.[Name 1], pn.[Sold-to address], np.[Created On]
      FROM NewProjects np
      WHERE np.[Sales Document] NOT IN
        (SELECT p.[Measure] FROM Projects p);