Saturday, February 25, 2012

Records NOT in OTHER table - SELECT statement

I am trying to compare 2 tables with similar data. One table has a field named [X Sent] and the other table has a field named [X Setup]. I was trying to extract all of the fields in Table 1 with field [X Sent] that are not yet in Table 2, i.e. field [X Setup]. I was trying some LEFT JOINS and other stuff but I can't seem to get the syntax correct. How can I get a query of only the fields that are not in Table 2, but are in Table 1?

Here are two of my attempts:

SELECT [X Sent], [X Date]
FROM [Table 1]
WHERE ([X Sent] NOT IN
(SELECT [Table 1].[X Sent]
FROM [Table 2] INNER JOIN
[Table 1] ON [Table 2].[X Setup]= [Table 1].[X Sent]))

I don't believe 'NOT IN' is proper syntax!

And my other attempt:

SELECT [Table 1].[X Sent]
FROM [Table 1] LEFT OUTER JOIN
[Table 2] ON [Table 2].[X Setup]= [Table 1].[X Sent]

Any help would greatly be appreciated.An outer join, checking for NULL in [Table 2] will do it.


SELECT [X Sent],[X Date] FROM
[Table 1] t1 LEFT OUTER JOIN [Table 2] t2 ON t1.[X Sent]=t2.[X Setup]
WHERE t2.[X Setup] IS NULL
|||Thanks once again Douglas Reilly!!!!

Greatly appreciative...|||After analyzing the data further, I have noticed that I can't only compare one field, but rather two from each table. I have been trying to work with the following statement, but I can't seem to get it to work. To start off with, I would like to capture all the fields where Field1 and Field2 from Table1 equals Field1 and Field2 of Table2.

SELECT [Field1], [Field2]
FROM Table1 t1 INNER JOIN
Table2 t2 ON t1.Field1 = t2.Field1 AND t1.Field2 = t2.Field2

Once I figure this part out, I will go ahead and search for all of these tuples not in the other table. Your assistance will greatly be appreciated.|||You should pick one of your candidate keys to be the primary key of Table1. Then you can do this:

select * from Table1
where Table1PrimaryKey not in
(select Table1PrimaryKey from Table1
inner join Table2 on Table1.Field1=Table2.Field1 and Table1.Field2=Table2.Field2)

If for some reason you really need the fields, you can use this:

select Table1.Field1, Table1.Field2
from Table1
inner join Table2 on Table1.Field1=Table2.Field1 and Table1.Field2=Table2.Field2

No comments:

Post a Comment