2016-10-23 54 views
1

比方說,我有3個表:SQL:2列1的結果集

info_contact:

id_contact  id_demand  email 
    1    1  [email protected] 
    2    2  [email protected] 
    3    3  [email protected] 

需求:

id_demand date 
    1  2016-10-12  
    2  2016-11-05  
    3  2016-12-12  

邀請:

id_invitation id_demand partner_company concurrent_company 
    1    1    google   facebook 
    2    1    null   linkedin 
    3    2    google    null 
    4    2    null    yahoo 
    5    3    google    null 

我想有那樣的結果:

 Company | id_demand 
    ---------------------- 
    Facebook |  1 
    Google |  1 
    Google |  2 
    Google |  3 
    Linkedin |  1 
    Yahoo |  2 

與(在一起的結果)partner_company和concurrent_company之間沒有什麼區別。

因爲我已經嘗試了一下:

SELECT i.partner_company, d.id_demand 
FROM info_contact as c, demand as d, invitation as i 
WHERE c.id_demand = d.id_demand AND d.id_demand = i.id_demand 
AND i.partner_company IS NOT NULL 
GROUP BY i.partner_company, d.id_demand; 

SELECT i.concurrent_company, d.id_demand 
FROM info_contact as c, demand as d, invitation as i 
WHERE c.id_demand = d.id_demand AND d.id_demand = i.id_demand 
AND i.concurrent_company IS NOT NULL 
GROUP BY i.concurrent_company, d.id_demand; 

,我不知道如何將這些2個查詢相結合,獲得的結果,我想

回答

4

嘗試使用UNION ALL

select partner_company , id_demand 
From invitation 
Where partner_company is not null 
Union All 
select concurrent_company , id_demand 
From invitation 
Where concurrent_company is not null 

另外我沒有JOIN其他表,因爲你沒有選擇他們。如果你想檢查存在,那麼JOIN它。使用INNER JOIN語法加入表

+0

Thx,它工作:) – isy