如何在单个列中获取多列的行值?

时间:2017-12-06 12:01:11

标签: mysql sql

我有两个表 tblCompany tblUser 两个表都包含电子邮件ID字段,tblCompany包含3列,名为 contact1Email,contact2Email,contact3Email ,tblUser包含名为 emailId 的列。两个表中的唯一字段是companyId。我想收到公司的电子邮件和用户的电子邮件,这些电子邮件属于该公司。我希望在一个列中的所有电子邮件ID。 我使用以下查询以基本方式尝试了它:

SELECT DISTINCT contact1Email , contact2Email, contact3Email, emailId
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33

这给出了如图所示的波纹管结果 enter image description here

你可以看到emailId列包含用户的电子邮件和contact1Email,contact2Email,contact3Email包含公司电子邮件。 我希望单列中的所有电子邮件都是名称emailIds。如何才能使用sql查询。?

我想要一个像

这样的结果
|EmailIds         |
|-------------------
|a@a.ll
|-------------------
|asdasdasd@asd.asd
|-------------------
|asdasdasd1@asd.asd
|-------------------
|aaaaa@a.ll
|-------------------
|asd@aswq.km
|-------------------
|aa@asd.ff
|-------------------

2 个答案:

答案 0 :(得分:2)

您可以使用concat_ws()将所有内容合并为一列:

SELECT DISTINCT CONCAT_WS(';', c.contact1Email , c.contact2Email, c.contact3Email, u.emailId) as emailIds
FROM fm_company c INNER JOIN
     fm_users u
     ON c.companyId = u.companyId
WHERE c.companyId = 33;

编辑:

在我看来,您希望每行中包含多行电子邮件。如果是这样的话:

select contact1Email as email
from company c
where c.companyId = 33
union -- on purpose to remove duplicates
select contact2Email as email
from company c
where c.companyId = 33
union
select contact3Email as email
from company c
where c.companyId = 33
union
select u.emailId
from fm_company c join
     fm_users u
     on c.companyId = u.companyId
where c.companyId = 33;

答案 1 :(得分:1)

试试这个:根据您的问题,您希望在单列中显示多列电子邮件ID,因此我认为您应该使用UNION OR UNION ALL来以下所需的格式实现所需的输出:

SELECT DISTINCT contact1Email
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33
UNION
SELECT DISTINCT contact2Email
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33
UNION
SELECT DISTINCT contact3Email
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33
UNION
SELECT DISTINCT emailId
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33