开发者

Reject row from select if condition exists in another table

开发者 https://www.devze.com 2023-03-19 04:12 出处:网络
开发者_开发百科I have two tables. Contacts table - contact_id, contact_email, contact_name, etc
开发者_开发百科

I have two tables.

  1. Contacts table - contact_id, contact_email, contact_name, etc
  2. Opt out table - contact_email, scope of their opt out (event, company)

So one contact maybe have multiple event opt-outs but what I really care about is if they have a company wide opt out.

How do I join the data so that if a contact has a match with any row in the optout table that has a scope of "company" it will not show up in the result?


SELECT c.*
    FROM Contacts c
    WHERE NOT EXISTS(SELECT NULL
                         FROM OptOut o
                         WHERE c.contact_email = o.contact_email
                             AND o.scope = 'company')

This could also be done with a LEFT JOIN:

SELECT c.*
    FROM Contacts c
        LEFT JOIN OptOut o
            ON c.contact_email = o.contact_email
                AND o.scope = 'company'
    WHERE o.contact_email IS NULL


select * from contacts where contact_email not in (select contact_email from optout where scope = 'company');

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号