views:

112

answers:

4

I have a list of e-mails from one database which I want to check against a list of unsubscribed e-mails from another database. If they exist in both lists, then I don't want them returned.

SELECT distinct `payer_email` as `email` 
FROM `database1`.`paypal_table`
WHERE `payer_email` != 
(SELECT `email` 
 FROM `database2`.`Unsubscribers` 
 WHERE `email` 
 LIKE `database1`.`paypal_table`.`payer_email`)
+4  A: 

Try:

`payer_email` NOT IN (SELECT `email` FROM `database2`.`Unsubscribers`)
Matt Schmidt
Thanks this did it.
Make sure you look at birdlips's answer using NOT EXISTS rather than NOT IN. Using IN can cause the query optimizer to read the sub query list for each record in the primary list.
Chris Porter
Thanks for the heads up. I didn't know the EXISTS clause...well, existed.
Matt Schmidt
+6  A: 

I would use:

WHERE NOT EXISTS (SELECT.....)

I have come to learn that EXISTS is better performing than IN when using larger data sets.

northpole
Is that true specifically for MySQL as well? It's certainly true for other DBs that recognise that pattern as fitting an anti-join plan.
araqnid
I have not done any tests of my own yet in MySQL. I had a conversation with my DBA yesterday and he discussed in detail how the two differ in terms of performance in ORACLE and SQL Server. We did not discuss MySQL but I assumed it was similar. I am looking now to try and find documentation on the latter.
northpole
northpole
A: 

Try this-

select distinct(email) from table 1 where email not in (select distinct(email) from table 2)
union
select distinct(email) from table 2 where email not in (select distinct(email) from table 1)

cheers

Andriyev
+1  A: 

You can do this with a join statement. Basically you try to join the two tables on their email addresses, and look at where the join failed to find a match.

SELECT DISTINCT email FROM table1
       LEFT JOIN table2 ON table1.email == table2.email
       WHERE table2.email IS NULL
Dietrich Epp