左连接两个表,然后只将新行附加到表

时间:2018-04-17 20:16:17

标签: sql ms-access

我正在尝试从tblForecast获取所有记录以及来自tblOpenJobs的匹配记录,并将它们附加到tblWorkingTable,但前提是tblWorkingTable中尚不存在[Job#]。

第一部分(通过第一个Left Join)工作正常,但第二个左连接和Where语句失败并出现语法错误:

  

查询表达式'A中的语法错误(缺少运算符)'[作业#] = B. [作业#] LEFT JOIN tblWorkingTable AS C ON A. [作业#] = C. [作业#'。

我对SQL很新,所以我不确定我哪里出错了。我可能会让它与两个单独的查询一起工作,但是将它全部用于一个查询是非常理想的。

INSERT INTO tblWorkingTable ( [Rec'd], ForecastMonth, [Ship Week], [Commit Date], [Job #], Customer, [Part #], Released, [Forecast Qty], [Actual Qty], Shipped, [Sales Price], [Sales Value], Invoice, Comments )
SELECT B.[Rec'd], A.ForecastMonth, A.[Ship Week], A.[Commit Date], A.[Job #], A.Customer, A.[Part #], B.Released, A.Qty AS [Forecast Qty], B.Qty AS [Actual Qty], B.Shipped, A.[Sales Price], A.[Sales Value], A.Invoice, A.Comments
FROM tblForecast AS A 
LEFT JOIN tblOpenJobs AS B ON A.[Job #] = B.[Job #]
LEFT JOIN tblWorkingTable AS C ON A.[Job #] = C.[Job #]
Where ((C.[Job #]) is Null);

是的,我知道,这些字段名称中不应该有特殊字符。我需要在数据导入期间为它们分配不同的名称。

1 个答案:

答案 0 :(得分:0)

MS Access需要在连接周围添加括号。试试这个:

INSERT INTO tblWorkingTable ( [Rec'd], ForecastMonth, [Ship Week], [Commit Date], [Job #], Customer, [Part #], Released, [Forecast Qty], [Actual Qty], Shipped, [Sales Price], [Sales Value], Invoice, Comments )
    SELECT B.[Rec'd], A.ForecastMonth, A.[Ship Week], A.[Commit Date], A.[Job #], A.Customer, A.[Part #], B.Released, A.Qty AS [Forecast Qty],
           B.Qty AS [Actual Qty], B.Shipped, A.[Sales Price], A.[Sales Value], A.Invoice, A.Comments
    FROM (tblForecast AS A LEFT JOIN
          tblOpenJobs AS B
          ON A.[Job #] = B.[Job #] 
         ) LEFT JOIN
         tblWorkingTable AS C
         ON A.[Job #] = C.[Job #]
    WHERE C.[Job #] is Null;