Forum Moderators: open

Message Too Old, No Replies

How to select record from one table which is absent in another table?

         

CheeryFox

7:10 am on Sep 21, 2008 (gmt 0)

10+ Year Member



There is table One from which I select records from time to time. The task is to select unique records. So I created table Two to which I save records having been choosen from table One previously. How to write query selecting records from table One which are absent in table Two?

ZydoSEO

1:32 pm on Sep 22, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I can think of two solutions...

You can use a NOT IN clause for this. Essentially you want to select rows from ONE where the primary key (fieldm in my examples below) for ONE is NOT IN TWO:

SELECT field1,field2,...,fieldn
FROM One
WHERE fieldm NOT IN (
SELECT fieldm FROM Two
)

NOT INs are not the most efficient clauses around. If you are dealing with very large tables and columns that are not indexed, it can run a long time.

The same thing can be accomplished with an OUTER JOIN. I don't have MySQL but off of the top of my head (without testing it) you could do something along the lines of:

SELECT field1, field2, ... , fieldn
FROM One AS o
LEFT JOIN Two AS t ON o.fieldm = t.fieldm
WHERE t.fieldm IS NULL

This should give you back rows from One that do not already exist in Two. Again this assumes that fieldm is the primary key for both tables.

[edited by: ZydoSEO at 1:38 pm (utc) on Sep. 22, 2008]

CheeryFox

10:19 am on Sep 29, 2008 (gmt 0)

10+ Year Member



ZydoSEO,
thanks for so detailed info.