Saturday 10 December 2011

Select data from table WHERE not matched in another table

The following SQL example allow you to select data, excluding data that is in another table.

You can off course include more selection criteria after the WHERE clause.

Code:   
--  Select data from table WHERE not matched in another table
SELECT data_from_table.*
FROM data_from_table
LEFT JOIN exclude_table
ON data_from_table.email = exclude_table.email
WHERE exclude_table.email IS NULL;

So, data will be selected where the email address does NOT match an email address in table exclude_table.

You can exclude multiple tables...
Code:   
--  Select data from table WHERE not matched in another table
SELECT data_from_table.*
FROM data_from_table
LEFT JOIN exclude_table_1
ON data_from_table.email = exclude_table_1.email
LEFT JOIN exclude_table_2
ON data_from_table.email = exclude_table_2.email
WHERE exclude_table_1.email IS NULL
AND exclude_table_2.email IS NULL;

So, data will be selected where the email address does NOT match an email address in table exclude_table_1 and does NOT match an email address in table exclude_table_2.

For speed, make sure that the field/s you’re comparing in both tables are keys.


No comments: