使用逗号连接多行上的多个字段

时间:2013-07-15 20:17:38

标签: php mysql join

我有2个表通过连接表连接。它们看起来像以下

      servers             serverInstances          instances
| id |     ip     |     | id | sID | iID |       | id | name |
|____|____________|     |____|_____|_____|       |____|______|
| 11 | 10.0.0.100 |     |  1 |  11 |  40 |       | 40 | real |
| 12 | 10.0.0.200 |     |  2 |  11 |  41 |       | 41 | fake |
                        |  3 |  12 |  45 |       | 45 | test |

通过以下查询,我可以获得以下数据

SELECT s.ip, i.name
FROM servers AS s
JOIN serverInstances AS si ON s.ID = si.sID
JOIN Instances AS i ON si.iID = i.ID


|     ip     | name |
|____________|______|
| 10.0.0.100 | real |
| 10.0.0.100 | fake |
| 10.0.0.200 | test |

我遇到的问题是,正在获取上述信息,并撰写将返回以下内容的查询。

|     ip     | instances  |
|____________|____________|
| 10.0.0.100 | real, fake |
| 10.0.0.200 |    test    |

是否有一种简单而动态的方式来编写此查询?

2 个答案:

答案 0 :(得分:3)

正如bwoebi在评论中所述,group_concat会给你这个。

SELECT s.ip,  group_concat(DISTINCT i.name ORDER BY i.name ASC SEPARATOR ", " ) as instances
FROM servers AS s
JOIN serverInstances AS si ON s.ID = si.sID
JOIN Instances AS i ON si.iID = i.ID 
GROUP BY s.ip;

答案 1 :(得分:1)

我认为这对你有用

SELECT s.ip, GROUP_CONCAT(i.name)
FROM servers AS s
JOIN serverInstances AS si ON s.ID = si.sID
JOIN Instances AS i ON si.iID = i.ID
GROUP BY s.ip