3

I want to pull all the unique IDs for particular rows with the same username and then display each result as a row.

For example...

Here's my table:

+----+------+
| id | name |
+----+------+
| 1  | Joe  |
| 2  | Amy  |
| 3  | Joe  |
| 4  | Amy  |
| 5  | Joe  |
| 6  | Amy  |
+----+------+

Here's the result I want:

+------+-------+
| name | ids   |
+------+-------+
| Joe  | 1,3,5 |
| Amy  | 2,4,6 |
+------+-------+

How do I pull this result in MySQL?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Adam
  • 1,887
  • 1
  • 21
  • 21
  • Might be able to do something like http://stackoverflow.com/questions/19558443/comma-separated-string-of-selected-values-in-mysql and include a way to do a group by name? – James Oravec Mar 22 '16 at 21:23
  • 1
    Possible duplicate of [Group by one column and Show all results from another column](http://stackoverflow.com/questions/17716854/group-by-one-column-and-show-all-results-from-another-column) – Serge Seredenko Mar 22 '16 at 21:29

3 Answers3

7

Use a GROUP_CONCAT() with DISTINCT clause to aggregate unique ids for a particular name:

SELECT name, GROUP_CONCAT(DISTINCT id SEPARATOR ',') AS ids
FROM yourtable
GROUP BY name

To review the usage of it also see MySQL group_concat with select inside select.

Community
  • 1
  • 1
Kamil Gosciminski
  • 16,547
  • 8
  • 49
  • 72
3

You can use group_concat for that:

SELECT   name, GROUP_CONCAT(id) AS ids
FROM     table
GROUP BY name

You can also specify a separator, but the one by default is the comma.

You can also specify DISTINCT, but since id is unique, there is no reason to this: all it will do is slow down the query.

Here is SQL fiddle producing the output as desired:

+------+-------+
| name | ids   |
+------+-------+
| Joe  | 1,3,5 |
| Amy  | 2,4,6 |
+------+-------+
trincot
  • 317,000
  • 35
  • 244
  • 286
1

This is a what the group_concat operator is designed for:

SELECT   name, GROUP_CONCAT(id) AS ids
FROM     mytable
GROUP BY name
Mureinik
  • 297,002
  • 52
  • 306
  • 350