简体   繁体   中英

How to select records present in one table which are not present in another table knowing that records can be kept in multiple fields

This question might have been asked already, but I haven't seen it. I need it for quality control purposes. One table is with the respondents we should send emails to, and the other one is the list of respondents who have unsubscribed, or who we have blacklisted.
There is a possibility that a respondent can have records in both tables (for example we have some email in the Respondents Email column, and the exact same email in the Unsubscribers Email 2 column etc.)

Table Respondents :
Name
Surname
Email
Email 2
Phone
Phone 2

Table Unsubscribers :
Name
Surname
Email
Email 2
Email 3
Email 4
Phone

Something like this should do it.

SELECT email from respondents LEFT JOIN unsubscribers u1 ON respondents.email = u1.email JOIN unsubscribers u2 on respondents.email = u2.email2 WHERE u1.email is null and u2.email2 is null

However, I would try to normalize your database. In your instance I would just add a date_unsubscribed field to the respondents table, it makes this sort of thing way easier and reduced database complexity and storage requirements.

NOT IN would be a typical approach:

select r.*
from respondents as r
where r.email not in (select email from unsubscribers) or
      r.email not in (select email2 from unsubscribers) or
      r.email not in (select email3 from unsubscribers) or
      r.email not in (select email4 from unsubscribers) or
      r.email2 not in (select email from unsubscribers) or
      r.email2 not in (select email2 from unsubscribers) or
      r.email2 not in (select email3 from unsubscribers) or
      r.email2 not in (select email4 from unsubscribers);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM