user677607
user677607

Reputation:

How can I select rows from a table that don't exist in another table?

I have 2 tables - first table holds all unique data (columns: title, artist, album). The second table has repeated data or people listening daily to an rss feed.

I want to save all the data from table2 to table1, but only if the row of table2 doesn't exist in table1. I want a sql query which will return all rows of table2 that aren't in table1 - how?

Upvotes: 2

Views: 4001

Answers (2)

Thomas
Thomas

Reputation: 64635

Assuming that the columns title, artist, album exist in Table2 and that you want to add all rows from Table2 where the given combination of those three do not exist in Table1, you can do something like:

Insert Table1( title, artist, album, ... )
Select title, artist, album, ...
From Table2
Where ( title, artist, album ) Not In   (
                                        Select title, artist, album
                                        From Table1
                                        )

Upvotes: 1

Matthew
Matthew

Reputation: 10444

Something like this, probably:

INSERT INTO Table1
(columns)
SELECT columns
FROM Table1
WHERE Table2.UniqueColumn NOT IN (SELECT UniqueColumn FROM Table1)

?

Upvotes: 4

Related Questions