0

我有 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    |

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

4

2 回答 2

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;
于 2013-07-15T20:25:09.977 回答
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
于 2013-07-15T20:22:52.323 回答