SQL:结果集中1列中的2列

时间:2016-10-23 17:09:04

标签: mysql sql join

我们说我有3张桌子:

info_contact:

 id_contact     id_demand       email 
     1             1        contact1@a.com
     2             2        contact2@a.com
     3             3        contact3@a.com

需求:

 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;

并且我不知道如何组合这两个查询并获得我想要的结果

1 个答案:

答案 0 :(得分: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语法加入表