0

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?

7
  • 2
    Look up the manual for GROUP_CONCAT Commented Jul 15, 2013 at 20:18
  • awesome. I will do that Commented Jul 15, 2013 at 20:19
  • 1
    @bwoebi You should post as the answer Commented Jul 15, 2013 at 20:22
  • @Orangepill wanted to give him only a hint, not the solution. People don't always need solutions. Commented Jul 15, 2013 at 20:24
  • I was able to make the solution myself! However if you post the solution i'll give it the checkmark Commented Jul 15, 2013 at 20:25

2 Answers 2

3

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.