简体   繁体   中英

Left join two tables, and then append only new rows to table

I'm trying to take all records from tblForecast and the matching records from tblOpenJobs and append them to tblWorkingTable, but only if the [Job #] does not yet exist in tblWorkingTable.

The first part (through the first Left Join) works fine, but the second left join and Where statement fail with a Syntax error:

Syntax error (missing operator) in query expression 'A.[Job #]= B.[Job #] LEFT JOIN tblWorkingTable AS C ON A.[Job #] = C.[Job#'.

I'm pretty new to SQL, so I'm not sure where I'm going wrong. I could probably get it to work with two separate queries, but it would be really ideal to get it all to work in one.

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);

And yes, I know, there shouldn't be special characters in those field names. I need to assign those a different name during the data import.

MS Access requires parentheses around joins. Try this:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM