2013-04-25 59 views
1

我有2個表,訂戶&發送日誌。我需要選擇所有訂閱者,但排除符合發送日誌表中的條件的記錄。從表A中選擇但排除表B中匹配的情況

的標準是,他們是一個「高級用戶」,該SubscribePreference = 1和,他們從來沒有收到一個「GoPro的」電子郵件

我這裏有一個SQL撥弄來表示,但不能找出查詢

http://sqlfiddle.com/#!3/3e1a7/6

在此示例中,我想回到大衛,埃德&弗蘭克因爲從未收到了「GoPro的」電子郵件

有人可以幫助我請在這裏?

回答

1

這應該工作:

SELECT DISTINCT s.EmailAddress 
    , 'GoPro' AS CampaignName 
    , sl.SendDate 
FROM Subscribers s 
LEFT JOIN SendLog sl 
    ON s.EmailAddress = sl.EmailAddress 
    AND CampaignName = 'GoPro' 
WHERE s.Entitlement = 'PowerUser' 
AND s.SubscribePreference = 1 
AND sl.EmailAddress IS NULL 

http://sqlfiddle.com/#!3/3e1a7/17

+0

感謝一羣完美工作 – user1735894 2013-04-25 23:32:44

0

我相信這將工作:

SELECT DISTINCT Subscribers.EmailAddress 
FROM Subscribers 
LEFT OUTER JOIN SendLog 
     ON Subscribers.EmailAddress = SendLog.EmailAddress 
     AND SendLog.CampaignName = 'GoPro' 
WHERE SendLog.EmailAddress IS NULL 
     AND Subscribers.SubscribePreference = 1 
     And Subscribers.Entitlement = 'PowerUser' 

出於性能的考慮,我建議增加一個ID列作爲主鍵認購表,然後在SendLog表中創建一個名爲SubscriberID的外鍵並將其加入。上面的查詢可以工作,但用整數和適當的鍵可以更快。

相關問題