2012-09-14 73 views
0

我有兩個mysql查詢返回一列電話號碼。我想試圖最終列出一個列表中的電話號碼,但不是另一個列表中的電話號碼。兩個select查詢之間的MySQL差異

所以這兩個查詢我的是:

SELECT phone 
FROM civicrm_phone phone 
LEFT JOIN civicrm_participant participant 
    ON phone.contact_id = participant.contact_id 
WHERE phone.is_primary = 1 
    AND participant.id IS NULL 

SELECT phone 
FROM civicrm_phone phone 
LEFT JOIN civicrm_participant participant 
    ON phone.contact_id = participant.contact_id 
WHERE phone.is_primary = 1 
    AND participant.id IS NOT NULL 

而且有人問之前,上述兩個查詢不提供相互排斥的結果(基於使用IS NULL和IS對於最後的WHERE語句,NOT NULL),因爲我們在數據庫中有相關的個人使用相同的電話號碼,但不一定都有一個participant.id。

感謝您的任何幫助。

+2

'SELECT * FROM list1 WHERE NOT IN(SELECT * FROM list2)'? – andrewsi

回答

4

下面的查詢提出第二次查詢的WHERE子句中的比較:

SELECT phone 
FROM civicrm_phone phone 
LEFT JOIN civicrm_participant participant ON phone.contact_id = participant.contact_id 
WHERE phone.is_primary = 1 
AND participant.id IS NULL and 
    not exists (SELECT 1 
       FROM civicrm_phone phone2 
       LEFT JOIN civicrm_participant participant ON phone2.contact_id = participant.contact_id 
       WHERE phone.is_primary = 1 
         AND participant.id IS NULL 
         and phone2.phone = phone.phone 
      ) 

通常在SQL,你不會在使用這個,但NOT EXISTS與相關子查詢是更有效MySQL的。