How to GROUP_CONCAT where there are null values in MYSQL?

送分小仙女□ 提交于 2019-12-11 15:08:33

问题


I have a long query that returns multiple values for a primary key (from a LEFT join). For example : (only showing two fields, but there about 10 fields)

LotID    Size
1         A
1         B 
1         C
2         null
3         B
4         A
4         B

When I use GROUP_CONACT, it returns as follows :

LotID       Size
1           A,B,C
3           B
4           A,B   

But what I actually want is :

LotID       Size
1           A,B,C
2           null
3           B
4           A,B   

I tried using

GROUP_CONCAT(CONCAT_WS(',', IFNULL(Size,''))) AS Sizes,

It returns :

    LotID       Sizes
    1           A,B,C,,,
    3           B,,
    4           A,B,,  

It does not return LotID=2, also aditional commas.

How could I do it to get clean records ?


回答1:


You must be doing something wrong with group_concat, because this:

select 
  lotid,
  group_concat(size) size
from tablename
group by lotid

returns:

| lotid | size               |
| ----- | ------------------ |
| 1     | A,B,C              |
| 2     | null               |
| 3     | B                  |
| 4     | A,B                |

See the demo.



来源:https://stackoverflow.com/questions/55442539/how-to-group-concat-where-there-are-null-values-in-mysql

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