MySQL GROUP_CONCAT with Nulls

坚强是说给别人听的谎言 提交于 2019-12-05 12:05:54

问题


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).


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/10336022/mysql-group-concat-with-nulls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!