如何在MYSQL中存在空值的GROUP_CONCAT? [英] How to GROUP_CONCAT where there are null values in MYSQL?

查看:1275
本文介绍了如何在MYSQL中存在空值的GROUP_CONCAT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长查询,该查询返回一个主键的多个值(来自LEFT联接)。
例如:(仅显示两个字段,但是大约有10个字段)

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

当我使用GROUP_CONACT时,返回如下:

When I use GROUP_CONACT, it returns as follows :

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

但是我真正想要的是:

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

我尝试使用

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

返回:

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

它不返回LotID = 2,

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

如何获取干净的记录?

推荐答案

您必须对group_concat做错事,因为这是

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

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

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

请参见演示

这篇关于如何在MYSQL中存在空值的GROUP_CONCAT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆