views:

50

answers:

5

I have 2 tables: #tmptable1 and #tmptable2. These tables have an ID to uniquely identify each record.

I want to return all records from table 1, but I only want to return the records from table 2 that aren't in table 1

I want this done in 1 query.

Thanks!

+3  A: 
SELECT * FROM '#tmptable1' 
UNION ALL
SELECT * FROM  '#tmptable2' WHERE 
    ID NOT IN (SELECT ID FROM #tmptable1 WHERE ID IS NOT NULL)
Martin Smith
+1 - And an EXISTS subclause would probably execute faster.
JNK
Will this work if the rows are different but could contain the same ID's. 1 column is different at the end.
+1  A: 

I don't quite understand what is it that you want to get in the results, but UNION selects distinct values, so you won't have duplicate values (values from #tmptable2 that already exist in #tmptable1).

SELECT * FROM #tmptable1
UNION
SELECT * FROM #tmptable2

Anyways, these records are records from #tmptable2 that aren't in #tmptable1.

SELECT * FROM #tmptable2
EXCEPT
SELECT * FROM #tmptable1
Hamid Nazari
Minus is Oracle only and the OP wants rows not just ids.
Martin Smith
@Matrin Thanks for noticing that. My bad. Fixed it.
Hamid Nazari
@Hamid - You would still need to include all records from `#tmptable1` somehow.
Martin Smith
+3  A: 

If all the other fields and data of the two tables is identical you could do this:

SELECT * FROM #tmptable1
UNION
SELECT * FROM #tmptable2

UNION without the ALL modifier removes duplicates.

Bill Karwin
beat me by 16 seconds
Conrad Frix
But that will still bring back 2 rows if the same id is in both tables and it has different values for the other columns. (unless of course there *are* no additional columns)
Martin Smith
@Martin Smith: True -- that's why the "if" in the first line of my post is important.
Bill Karwin
@Bill - Apologies. I must confess I didn't read that.
Martin Smith
@Martin Smith: No problem, it's a good point worth emphasizing.
Bill Karwin
They are in fact different. The last column contains a different note so I need just when the ID's are the same...?
@anicolais: Then go with @Martin Smith's answer.
Bill Karwin
A: 

This is what UNION does

SELECT * FROM '#tmptable1' 
UNION 
SELECT * FROM  '#tmptable2'
Conrad Frix
A: 
SELECT ID FROM #tmptable1
UNION
SELECT ID FROM #tmptable2

The UNION operator will automatically remove duplicates.

Toby