views:

38

answers:

1

Hi all,

I am trying to create a MySQL SELECT statement that will select a bunch of rows from a table and will group the results by the id of the row (multiple rows will have the same id).

Here's an example of what I'm trying to do. Let's say I have the following table:

id | name
1 | Art
1 | Arnold
1 | Anatoly
2 | Beatrice
2 | Bertha
2 | Betty
3 | Constantine
3 | Cramer

I'd like to have MySQL return the data grouped by id like so:

[1] => Art, Arnold, Anatoly [2] => Beatrice, Bertha, Betty [3] => Constantine, Cramer

I know I could do a simple SQL select, then loop over the result in PHP, but I'd like to let MySQL handle the grouping if possible. Any advice would be great. Thanks so much!

Rohan

+3  A: 

One possible solution is to use MySQL's GROUP_CONCAT(expr) function.

SELECT
  GROUP_CONCAT(name)
FROM
  foo
GROUP BY
  id

But keep in mind:

The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024.
VolkerK
That 1024 value has come back to haunt me many times.
Mike B
@MikeB, it haunts me everyday: I was born on 10/24. :P
Alix Axel
thanks for the reply @VolkerK, but I will definitely run into the max length issue since I'm dealing with thousands of rows =)
@user why do you need such amount of data? what you gonna do with a line containing thousand of comma-separated names?
Col. Shrapnel
@user259878: the variable can be changed in the current session by `SET @@group_concat_max_len:= 1024*100;`, up to 4294967295. But the question of Col. Shrapnel is still relevant.
newtover