如何将GROUP_CONCAT添加到UNION查询?

时间:2012-12-19 16:44:01

标签: mysql

我有以下查询可以正常收到正确的电子邮件,给出以下结果: - user1@company.com - user2@company.com - 等等

问题:如何添加MySQL GROUP_CONCAT 功能,以便用逗号分隔结果: - user1 @ company.com,user2 @ company.com等

以下是我的联盟查询的一部分:

- 当我向其提供票号时,它会检查票证号码上的票证类型值。返回那些在后端表中检查了该类型的用户。

SELECT CONCAT(tblemailaction.uea_User, "@company.com") AS User_email,                 tblemailaction.uea_ADSL
FROM tblemailaction, tbltickets, tbltickettype
WHERE tbltickets.ttType = tbltickettype.ttDesc
 AND tbltickettype.ttID = tblemailaction.uea_ADSL
 AND ttNum = <cfqueryparam cfsqltype="cf_sql_integer" value="#url.id#">


UNION ALL


SELECT CONCAT(tblemailaction.uea_User, "@company.com") AS User_email,          tblemailaction.uea_ADSL_INSTALL
FROM tblemailaction, tbltickets, tbltickettype
WHERE tbltickets.ttType = tbltickettype.ttDesc
 AND tbltickettype.ttID = tblemailaction.uea_ADSL_INSTALL
 AND ttNum = <cfqueryparam cfsqltype="cf_sql_integer" value="#url.id#">

UNION ALL


SELECT CONCAT(tblemailaction.uea_User, "@company.com") AS User_email, tblemailaction.uea_Cabling
FROM tblemailaction, tbltickets, tbltickettype
WHERE tbltickets.ttType = tbltickettype.ttDesc
 AND tbltickettype.ttID = tblemailaction.uea_Cabling
 AND ttNum = <cfqueryparam cfsqltype="cf_sql_integer" value="#url.id#">


UNION ALL


SELECT CONCAT(tblemailaction.uea_User, "@company.com") AS User_email, tblemailaction.uea_Calix
FROM tblemailaction, tbltickets, tbltickettype
WHERE tbltickets.ttType = tbltickettype.ttDesc
 AND tbltickettype.ttID = tblemailaction.uea_Calix
 AND ttNum = <cfqueryparam cfsqltype="cf_sql_integer" value="#url.id#">

1 个答案:

答案 0 :(得分:2)

首先,请注意GROUP_CONCAT函数受max_allowed_packet变量的值限制,该变量通常设置为1048576(即1MB)。当然,这个变量的值可以增加,但要注意有一个限制。

快速回答是将整个查询“包装”在一组括号中,并将其作为查询中的行源引用。基本上,将您的查询转换为“内联视图”。

SELECT GROUP_CONCAT(v.User_email)
  FROM (
         /* your UNION ALL query here */
       ) q

要删除重复项,可以使用DISTINCT关键字。要获取特定序列中的值,可以使用ORDER BY子句。

SELECT GROUP_CONCAT(DISTINCT v.User_email ORDER BY v.User_email)
  FROM (
         /* your UNION ALL query here */
       ) q

再次注意,GROUP_CONCAT函数返回的字符串长度受max_allowed_packet值的限制。


后续问:如何从列表中“排除”或过滤掉电子邮件..例如: - 如果SESSION.kt_email =“列表中的某个电子邮件”那么从列表中删除

答:快速回答就是例子。如果您想要排除一个电子邮件地址,请说'foo',为此示例:

SELECT GROUP_CONCAT( NULLIF(v.User_email,'foo') )
  FROM (
         /* your UNION ALL query here */
       ) q

这里的技巧是我们用'foo'替换NULL的任何值,GROUP_CONCAT将“跳过”任何NULL值并将它们从返回字符串中排除。

表达式:

    NULLIF(v.User_email,'foo')

是:

的简写
    IF(v.User_email='foo',NULL,v.User_email)

相当于(ANSI标准越多):

    CASE WHEN v.User_email = 'foo' THEN NULL ELSE v.User_email END

当然,你要用你想要排除的字符串值或表达式替换文字'foo'(在我的例子中)。