单个select语句中有多个GROUP_CONCAT

时间:2013-08-23 21:03:25

标签: php mysql group-concat

我的查询类似于以下

SELECT s.ip, 
    t.name AS 'typeName', 
    e.name AS 'envName',
    i.name,
    s.computerName
    #ap.name
    #GROUP_CONCAT(DISTINCT i.name ORDER BY i.name ASC SEPARATOR ', ' ) AS instances
    #GROUP_CONCAT(ap.name ORDER BY ap.name ASC SEPARATOR ', ' ) AS AppPool
FROM servers AS s 
JOIN types AS t ON s.typeID = t.id
JOIN environments AS e ON s.envID = e.id
JOIN serverinstances AS si ON s.id = si.serverID
JOIN instances AS i ON si.instanceID = i.id
JOIN serverapppool AS sa ON s.id = sa.serverID
JOIN apppools AS ap ON sa.appPoolID = ap.id
WHERE computerName IS NOT NULL

以上查询的结果

|     ip      | type | env | instance | appPool | compName |
|_____________|______|_____|__________|_________|__________|
| 192.168.1.1 |  App | test|   com1   |   fo    |   name1  |
| 192.168.1.1 |  App | test|   com1   |   bo    |   name1  |
| 192.168.1.1 |  App | test|   com2   |   fo    |   name1  |
| 192.168.1.1 |  App | test|   com2   |   bo    |   name1  |
| 192.168.1.2 |  App | test|   com1   |   fo    |   name2  |
| 192.168.1.2 |  App | test|   com1   |   bo    |   name2  |
| 192.168.1.2 |  App | test|   com2   |   fo    |   name2  |
| 192.168.1.2 |  App | test|   com2   |   bo    |   name2  |
| 192.168.1.3 |  App | prod|   com1   |   fo    |   name3  |
| 192.168.1.4 |  App | prod|   com1   |   fo    |   name4  |
| 192.168.1.5 |  App | prod|   com1   |   bo    |   name5  |

这些结果是准确的。但是我需要压缩它们。目标是让它们看起来像下面的

|     ip      | type | env |  instances  | appPools | compName |
|_____________|______|_____|_____________|__________|__________|
| 192.168.1.1 |  App | test| com1, com2  |  fo, bo  |   name1  |
| 192.168.1.2 |  App | test| com1, com2  |  fo, bo  |   name2  |
| 192.168.1.3 |  App | prod|    com1     |    fo    |   name3  |
| 192.168.1.4 |  App | prod|    com1     |    fo    |   name4  |
| 192.168.1.5 |  App | prod|    com1     |    bo    |   name5  |

我相信这可以通过使用GROUP_CONCAT来完成,正如您在第一个查询中看到的那样,我尝试了各种各样的事情。但无法让它产生所需的结果。思考?

1 个答案:

答案 0 :(得分:2)

GROUP中的GROUP_CONCAT会给您提示 - 您实际上并未对查询中的任何内容进行分组,例如没有GROUP BY条款。由于您还没有告诉MySQL您的数据应该如何分组,因此它没有进行任何分组。因此,只能从GROUP_CONCAT调用中获取单个值。

您很可能想要更像

的内容
SELECT s.ip
etc..
etc..
GROUP BY s.ip  <---this line is missing