我有两个表 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
你可以看到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
|-------------------
答案 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