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?
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With