Reputation: 3083
I have 2 tables connected by a join table. They look like the following
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 |
With the below query I can get the below data
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 |
What I am having trouble with, is taking the above information, and writing a query that would return the following.
| ip | instances |
|____________|____________|
| 10.0.0.100 | real, fake |
| 10.0.0.200 | test |
Is there an easy yet dynamic way to do write this query?
Upvotes: 0
Views: 80
Reputation: 24655
As bwoebi stated in comments group_concat will give you this.
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;
Upvotes: 3
Reputation: 692
I think this will work for you
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
Upvotes: 1