PHP MYSQL COMBINE STRING

54 Views Asked by At
Table `names`
ID | name 
---------
1  | Alex
2  | John
3  | Alex
4  | Alex
5  | Alice
6  | Monica

SELECT `name` FROM `names` GROUP BY `name`
Alex
John
Alice
MOnica

so, I need to make like this

SELECT `name`, COMBINE_STRING(`ID`, SEPARATOR `,`) AS `IDS` FROM `names` GROUP BY `name`

and the result should be like this : 

and the result will be like this :

NAME | IDS
------------
Alex   1,3,4
John   2
Alice  5
MOnica 6

but as you see that mysql function COMBINE_STRING doesn't exist, so any ideas how to do this?

2

There are 2 best solutions below

2
On BEST ANSWER

Simply you can use GROUP_CONCAT function of MySql which'll work for you as like of your COMBINE_STRING

SELECT `name`, GROUP_CONCAT(`ID`) AS `IDS` FROM `names` GROUP BY `name`
0
On

Change COMBINE_STRING to group_concat so it becomes

SELECT `name`, group_concat(`ID`) AS `IDS` FROM `names` GROUP BY `name`

, is default separator for the group_concat when explicitly not provided.