Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL column data returned as comma delimited list

Tags:

mysql

I currently have a MySQL table like:

id | friend
1  |   2
1  |   5
1  |   10
3  |   6
15 |   19
21 |   4

I'm trying to grab all the friend id's of one particular user and arrange them into a comma-delimited list. For example, grabbed user1's friends, it would return as

$friend_list = 2,5,10

Currently, I have:

$sql = "SELECT friend FROM table__friends WHERE id = ".$user_id;

This only grabs one row though..please help!

Thanks

like image 679
Delos Chang Avatar asked Jun 11 '12 20:06

Delos Chang


1 Answers

You want to use GROUP_CONCAT :

$sql = "SELECT GROUP_CONCAT(friend) FROM table__friends GROUP BY id HAVING id = ".$user_id;

Adjusted for correctness per the better answer.

like image 169
GDP Avatar answered Oct 27 '22 10:10

GDP