Is there an option to make MySQL's Group_Concat function include nulls?
Consider the following example from my source table:
userId, questionId, selectionId 7, 3, NULL 7, 4, 1 7, 5, 2
When I query on the selection table with GROUP_CONCAT, I get the following:
7, 4=1,5=2
I would like to get the following:
7, 3=NULL,4=1,5=2
For reference, my query looks like this:
Select userId, GROUP_CONCAT(CONCAT(questionId, '=', selectionId)) From selection Group by userId;
I also tried adding an IFNULL like this:
Select userId, GROUP_CONCAT(IFNULL(CONCAT(questionId, '=', selectionId), 'NULL')) From selection Group by userId;
but that produced the following:
7, NULL,4=1,5=2
Note - There is one other complexity that I forgot to include. The selectionId is a foreign key to another table. I use a left outer join to the selection_text table. My real query includes fields from that table (these fields resolve to NULL since the selectionId is null).
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.
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.
MySQL has the GROUP_CONCAT() function that allows us to output our query results in a comma separated list: SELECT GROUP_CONCAT(PetName) FROM Pets; Oracle Database. SQL Server.
You should just IFNULL
the column that can be NULL
;
SELECT userId, GROUP_CONCAT(CONCAT(questionId, '=', IFNULL(selectionId, 'NULL'))) FROM selection GROUP BY userId;
Demo here.
You should use IFNULL
or COALESCE
on the selectionId
value directly:
SELECT userId, GROUP_CONCAT(CONCAT(questionId, '=', COALESCE(selectionId, 'NULL'))) FROM selection GROUP BY userId;
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