Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate fields in Mysql

I have a table like this

id   name   value
1    Ram     a
2    John    b
3    Ram     c
4    Ram     d
5    John    e

I want the the output like this

name   value
Ram     a,c,d
John    b,e

Is there any way to perform this query?

UPDATE :

Table format :

id   field1   value  field2
1    val1     a       null
2    val2     b       null
3    val1     c       null
4    val2     d       null
5    null     e       val1
5    null     f       val1
5    null     g       val2
5    null     h       val2

Output :

field1   field2   value
val1      null    a,c
val2      null    b,d
null      val1    e,f
null      val2    g,h

Is there any way to perform this ?

like image 852
Pranav C Balan Avatar asked Dec 25 '22 18:12

Pranav C Balan


1 Answers

You can use group_concat

select
name, group_concat(value separator ',') as value
from table_name
group by name

Also if you want the values to be ordered you can use order by within group concat as

select
name, group_concat(value order by value) as value
from table_name
group by name
like image 186
Abhik Chakraborty Avatar answered Dec 27 '22 18:12

Abhik Chakraborty