我有一张表格,上面写满了一家公司的电话号码。 我的问题是,员工的每个号码都有一行,所以如果他有一部主电话和一部手机,我们就有两行他。
现在我需要显示所有员工的列表,包括他们的电话号码和手机号码(如果有的话)和电子邮件,但电子邮件在另一个表中。 我正在使用 SQL。
一个例子:
电话 table
ID | EmpID | FullName | Number | Type |
----------------------------------------------------------------
115 | 02 | ManuelSan | +34935556663 | Fix |
116 | 02 | ManuelSan | +34652315453 | Mobile |
117 | 06 | Camillete | +34934445621 | Fix |
118 | 07 | MarcusEsq | +34932547841 | Fix |
119 | 08 | FionaYem | +34965214785 | Fix |
120 | 08 | FionaYem | +34652132124 | Mobile |
电子邮件表
ID | empID | Fullname | Email |
-----------------------------------------------------------------
25 | 02 | ManuelSan | Manuelsan@gg.com |
26 | 06 | Camillete | Camillete@gg.com |
27 | 07 | MarcusEsq | MarcusEsq@gg.com |
28 | 08 | FionaYem | FionaYem@gg.com |
所以我想要这个输出
Fullname | Fix | Mobile | Email
------------------------------------------------------------------
ManuelSan | +34935556663 | +34652315453 | Manuelsan@gg.com
Camillete | +34934445621 | NULL | Camillete@gg.com
MarcusEsq | +34932547841 | NULL | MarcusEsq@gg.com
FionaYem | +34965214785 | +34652132124 | FionaYem@gg.com
但我这样做:
SELECT distinct telf.Fullname, telf.Number, acti.EMAIL
FROM PhoneTable telf
left outer join EmailTable as acti on acti.empID = telf.empID
我知道我需要做点别的,但我不知道该做什么。如果每个员工都有电话和手机,我会得到两行。
我应该怎么做?
问候,
最佳答案
大量冗余数据,可能不一致;然而,如果我们假设 empid
定义了姓名并且 PhoneTable
包含每个员工的条目,则查询可能如下所示。查询的第一部分将一个员工的不同记录合并为一个记录;左外连接然后获取相应的电子邮件。请注意,如果有员工有电子邮件但连一个电话号码都没有,则查询仍未完成:
select *
from (select empid,
max(fullname),
max(case when type='Fix' then Number else NULL end) as fix,
max(case when type='Mobile' then Number else NULL end) as Mobile
from PhoneTable
group by empid) phone
left outer join EMailTable e on phone.empid=e.empid
关于mysql - SQL如何正确地进行外部连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44544462/