Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL GROUP_CONCAT multiple fields

I'm probably having a no-brain moment.

I want to return a series of numbers using GROUP_CONCAT from two fields in my database. I have done this so far using the following:

SELECT t_id,
CONCAT(GROUP_CONCAT(DISTINCT s_id),',',IFNULL(GROUP_CONCAT(DISTINCT i_id),'')) AS all_ids
FROM mytable GROUP BY t_id

This works fine but if i_id is NULL then of course I get an unnecessary comma. Is there a better way to do this so I don't end up with a comma at the end if i_id is NULL?

like image 606
Pandy Legend Avatar asked Oct 08 '12 12:10

Pandy Legend


People also ask

Is there a limit to Group_concat?

The GROUP_CONCAT() function has a default length of 1024 characters, which is controlled by the global variable group_concat_max_len . If the joined values length is greater than the group_concat_max_len value, then the result string will be truncated.

What is the difference between concat and Group_concat in MySQL?

The difference here is while CONCAT is used to combine values across columns, GROUP_CONCAT gives you the capability to combine values across rows. It's also important to note that both GROUP_CONCAT and CONCAT can be combined to return desired results.

What does Group_concat do in MySQL?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.


1 Answers

You need to use CONCAT_WS to avoid extra comma for NULL values, try this:

SELECT t_id,
       CONCAT_WS(',', GROUP_CONCAT(DISTINCT s_id),
                 GROUP_CONCAT(DISTINCT i_id)) AS all_ids
FROM mytable
GROUP BY t_id;
like image 138
Omesh Avatar answered Sep 28 '22 09:09

Omesh