Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: select emails from one table only if not in another table?

Tags:

mysql

I am going to build a table called donotemail that will contain the email addresses of people who ask to be removed from our email list. I have another table called users with an email column. How can I select all the emails from users but only if the email address is not in the donotemail table?

Thanks!

like image 670
JD Isaacks Avatar asked Jun 16 '09 16:06

JD Isaacks


People also ask

How do I find records in one table but not another in SQL?

How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.


2 Answers

Try

SELECT Email.address
FROM Email LEFT OUTER JOIN DoNotMail on Email.address = DoNotMail.address
WHERE DoNotMail.address is null

It avoids needing a subquery.

like image 185
Kothar Avatar answered Oct 17 '22 15:10

Kothar


 select u.email from users u where u.email not in (select email from donotemail)

OR

select u.email from users u inner join donotemail d on u.email != d.email

EDIT: The join doesn't work

like image 3
Byron Whitlock Avatar answered Oct 17 '22 14:10

Byron Whitlock