![](/img/trans.png)
[英]How to select records from one table in which other record should not be present in it
[英]How to select records present in one table which are not present in another table knowing that records can be kept in multiple fields
這個問題可能已經被問過了,但是我還沒有看到。 我需要它來進行質量控制。 一個表是我們應該向其發送電子郵件的響應者,另一個是未訂閱或被列入黑名單的響應者的列表。
受訪者有可能在兩個表中都有記錄(例如,我們在“受訪者電子郵件”列中有一些電子郵件,在“退訂者電子郵件2”列中有完全相同的電子郵件,等等)。
表受訪者 :
名稱
姓
電子郵件
電郵2
電話
電話2
表退訂者 :
名稱
姓
電子郵件
電郵2
電郵3
電郵4
電話
這樣的事情應該做。
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
但是,我會嘗試規范化您的數據庫。 在您的實例中,我只是將一個date_unsubscribed字段添加到受訪者表中,這使這種事情變得更容易,並降低了數據庫的復雜性和存儲要求。
NOT IN
是一種典型的方法:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.