MySQL COUNT,GROUP_CONCAT和GROUP BY在一起

时间:2014-06-24 10:25:23

标签: php mysql

我有一个类似于MySQL的表。

IP Host Label BotName
1  A    good    aa
1  A    good    aa
2  C    good    bb
3  C    bad     cc
4  D    bad     dd
4  D    bad     ee
5  E    good    ff
5  E    good    gg

我希望获得如下输出。

count Host BotName  Type
2     A    aa       good
1     C    bb       good
1     C    cc       bad
2     D    dd,ee    bad
2     E    ff,gg    good

条件是:

  1. 按主机和标签计算IP组
  2. 如果机器人名称不同,请使用逗号连接它们。
  3. 以下是我尝试过的,但无法获得预期结果。

    $result2 = mysql_query("SELECT GROUP_CONCAT(BotName) name FROM (SELECT *, COUNT(IP) FROM mytable GROUP BY Host,Label)q");
    

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT COUNT(*) AS `count`,
       HOST,
       GROUP_CONCAT(distinct boatname) BotName,
       label as Type
FROM temp
GROUP BY host,label

SQL Fiddle

答案 1 :(得分:1)

Count和GROUP_CONCAT将获取值,但您需要按主机和标签/类型字段进行分组。

SELECT  COUNT(*) AS `count`, Host, GROUP_CONCAT(DISTINCT Botname) AS Botname, label AS type
FROM name
GROUP BY Host, type