【问题标题】:group_concat filteringgroup_concat 过滤
【发布时间】:2013-07-05 11:31:04
【问题描述】:

我不知道该如何查询。

表 1

id    client_name   Group_id     
------------------------------
1     IBM               1
2     DELL              1   
3     DELL              2
4     MICROSOFT         3 
5     DELL              2
6     MICROSOFT         2
7     HP                3 
7     HP                1

表 2

id    group_name
------------------
1     Group1      
2     Group2     
3     Group3  

使用下面的查询。

SELECT Client_name, GROUP_CONCAT(distinct(group_name)) merge_group , count(distinct(group_name)) as num_groups
FROM Table1 t1
JOIN Table2 t2
  ON t1.group_id = t2.id
GROUP BY t1.Client_name
ORDER BY t1.Id having num_groups > 1

将由此产生

client_name      merge_group   
-------------------------
DELL               Group1,Group2
MICROSOFT          Group2,Group3
HP                 Group1,Group3

如果我选择 Group2,我需要过滤 merge_group

结果是这样的

client_name      merge_group   
-------------------------
DELL               Group1,Group2
MICROSOFT          Group2,Group3

或者如果我查询 Group1,结果是这样的。

client_name      merge_group   
-------------------------
DELL               Group1,Group2
HP                 Group1,Group3

【问题讨论】:

    标签: mysql group-by filtering


    【解决方案1】:

    试试下面:

    SELECT Client_name, GROUP_CONCAT(distinct(group_name)) merge_group , count(distinct(group_name)) as num_groups
    FROM Table1 t1
    JOIN Table2 t2  ON t1.group_id = t2.id
    GROUP BY t1.Client_name
    HAVING num_groups > 1
    AND merge_group LIKE '%Group1%'
    

    【讨论】:

    • 太棒了!...我一直在寻找这个
    【解决方案2】:

    只需引入 where 子句并过滤组名即可。

    SELECT Client_name, GROUP_CONCAT(distinct(group_name)) merge_group , count(distinct(group_name)) as num_groups
    FROM Table1 t1
    JOIN Table2 t2
      ON t1.group_id = t2.id
    WHERE group_name = 'Group1' 
    GROUP BY t1.Client_name
    ORDER BY t1.Id having num_groups > 1
    

    您也可以使用HAVING 子句进行字符串比较。

    【讨论】:

      【解决方案3】:

      FIND_IN_SET() 方法也可以用于这种情况下的过滤。可以这样做:

      SELECT
          client_name
          , GROUP_CONCAT(DISTINCT group_name) AS merge_group
          , COUNT(DISTINCT group_name) AS num_groups
      FROM table1 AS t1
      JOIN table2 AS t2 ON t1.group_id = t2.id
      GROUP BY t1.client_name
      HAVING num_groups > 1
      AND FIND_IN_SET('Group1', merge_group)
      

      逗号用作GROUP_CONCAT() 的默认分隔符,因此可以将每个组过滤为一组。在许多情况下,它比REGEXPLIKE 更安全。他们在字符串中搜索在上述情况下可以轻松使用的单词,但在大型数据集上使用会很冒险,其中一个组名是另一个组名的子字符串。

      【讨论】:

        猜你喜欢
        • 2021-02-24
        • 2017-04-25
        • 1970-01-01
        • 2012-11-11
        • 2018-09-21
        • 2011-01-31
        • 1970-01-01
        • 2013-03-28
        • 2019-07-08
        相关资源
        最近更新 更多