2016-04-06 80 views
0

我試圖完成MySQL中多個表的聯接。我已成功地編寫以下查詢:MySQL加入忽略具有空電子郵件列值的行

SELECT 
    CONCAT(c.first_name, ' ', c.last_name) as name, 
    c.title, 
    c.department, 
    CONCAT(c2.first_name, ' ', c2.last_name) as reports_to, 
    c.phone_work, 
    c.phone_mobile, 
    e.email_address 
FROM 
    email_addresses e, 
    email_addr_bean_rel eb, 
    contacts c 
LEFT JOIN 
    contacts c2 ON c.reports_to_id = c2.id 
WHERE 
    c.id = eb.bean_id and 
    e.id = eb.email_address_id; 

這是生產與我所需要的數據的表,唯一的問題是,這並不包括聯繫人的完整列表。當我做了一個聯繫人的計數有130但是與上面的查詢結果減少到86.

經過一番調查後,我發現這是由於沒有被忽略的電子郵件地址的聯繫人,我不想要這個,但不知道如何阻止他們被忽略,如果他們有一個空條目。

email_addresses表包含電子郵件地址,但使用得到email addresscontact查找必須做在email_addr_bean_relcontactsid第一

回答

1
SELECT CONCAT_WS(' ',c.first_name,c.last_name) name 
    , c.title 
    , c.department 
    , CONCAT_WS(' ',c2.first_name,c2.last_name) reports_to 
    , c.phone_work 
    , c.phone_mobile 
    , e.email_address 
    FROM contacts c 
    LEFT 
    JOIN email_addr_bean_rel eb 
    ON eb.bean_id = c.id 
    LEFT 
    JOIN email_addresses e 
    ON e.id = eb.email_address_id 
    LEFT 
    JOIN contacts c2 
    ON c2.id = c.reports_to_id 
+0

這看起來很多更好 - 但是當我做了計數有四個額外的條目比接觸表保存。任何想法爲什麼這可能是? – algorhythm

+1

也許一個聯繫人有多個電子郵件地址 – Strawberry

+0

是的,4個重複。謝謝 – algorhythm

1

我覺得你的問題是表的順序加入。因此,例如,如果您想列出所有聯繫人,無論是否使用電子郵件,聯繫人都應該是您的第一個表格。所以,我會用從JaydipJ查詢,有一個小的修改:

SELECT 
CONCAT(c.first_name, ' ', c.last_name) as name, 
c.title, 
c.department, 
CONCAT(c2.first_name, ' ', c2.last_name) as reports_to, 
c.phone_work, 
c.phone_mobile, 
e.email_address 
FROM 
contacts c 
LEFT JOIN email_addr_bean_rel eb ON c.id = eb.bean_id 
LEFT JOIN email_addresses e ON e.id = eb.email_address_id 
LEFT JOIN contacts c2 ON c.reports_to_id = c2.id 
相關問題