Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MySQL How do I SELECT all ids from rows with a similar value

Tags:

sql

select

mysql

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?

like image 769
Adam Avatar asked Dec 05 '25 10:12

Adam


1 Answers

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.

like image 124
Kamil Gosciminski Avatar answered Dec 08 '25 01:12

Kamil Gosciminski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!