Mysql union如何将返回的3行分组为单行
Posted
技术标签:
【中文标题】Mysql union如何将返回的3行分组为单行【英文标题】:Mysql union how to Group returned 3 rows into single row 【发布时间】:2014-01-26 05:51:54 【问题描述】:mysql union 如何将返回的3行分组为单行
(
select CONCAT(c.Email,';', c.CCEmail,';', c.AdminEmail,';', c.HREmail) as Email
from companies c
Where companyid=#companyid#
)
union
(
select ClaimAdministratorEmail
from claimadminregion
where FIND_IN_SET(#companyid#, companyid)
)
union
(
select LossPreventionPersonEmail
from losspreventionregion
where FIND_IN_SET(#companyid#, companyid)
)
它返回 3 行,但我希望它们在单行中,但不知道如何
【问题讨论】:
您的最终目标是什么?为什么查询必须返回一行? 【参考方案1】:试试这个:
SELECT CONCAT(c.Email,';', c.CCEmail,';', c.AdminEmail,';', c.HREmail,';', A.ClaimAdministratorEmail,';', B.LossPreventionPersonEmail) AS Email
FROM companies c
LEFT JOIN (SELECT #companyid# AS companyid, GROUP_CONCAT(ClaimAdministratorEmail SEPARATOR ';') ClaimAdministratorEmail
FROM claimadminregion WHERE FIND_IN_SET(#companyid#, companyid)
) A ON c.companyid = A.companyid
LEFT JOIN (SELECT #companyid# AS companyid, GROUP_CONCAT(LossPreventionPersonEmail SEPARATOR ';') LossPreventionPersonEmail
FROM losspreventionregion WHERE FIND_IN_SET(#companyid#, companyid)
) B ON c.companyid = B.companyid
WHERE companyid=#companyid#
【讨论】:
claimadminregion -> claimadminregion as A, losspreventionregion -> losspreventionregion as B, WHERE companyid=#companyid# -> WHERE c.companyid=#companyid#, but not working return NULL 我们不能像SELECT #companyid#那样使用它,#companyid#被用作可验证的 @Rik 我们可以使用#companyid#
作为列,但我们必须为该列指定ALIAS
名称。我已经更新了那部分。这是必要的,因为我们想将companyid
与companies
表的主键进行比较以上是关于Mysql union如何将返回的3行分组为单行的主要内容,如果未能解决你的问题,请参考以下文章