asep komarudin asep komarudin - 2 months ago 7
MySQL Question

Get 2 or more data from 1 id in 1 table

i need help about sql query..
Sorry but I do not know much about sql, and I'm bad with english.

I have sql table like this.

| ID | Data |
| 1 | abc |
| 1 | def |
| 1 | ghi |
| 2 | jkl |
| 2 | mno |
| 3 | pqr |
| 3 | stq |



and i want result like this

| ID | Data |
| 1 | abc, def, ghi |
| 2 | jkl, mno |
| 3 | stq, def |



or like this

| ID | Data1 | Data2 | Data3 |
| 1 | abc | def | ghi |
| 2 | jkl | mno |
| 3 | pqr | stq |




I hope someone can help me. Thanks.

Answer

For mysql:

group_concat is your friend.

This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.

SELECT id, group_concat(data) as data from my_table group by id

this produces results of the type in your first sample. The second sample output is more complicated,

Comments