Mysql查询从多列内容连接不同的值,不带null和空

时间:2015-06-26 01:37:05

标签: mysql

我正在尝试合并多列的内容。当我尝试使用以下内容时:

GROUP_concat(DISTINCT case when companylocation.Mobile is null then '' else companylocation.Mobile end, 
    case when companylocation.Mobile2 is null then '' else companylocation.Mobile2 end,
    case when companylocation.Mobile3 is null then '' else companylocation.Mobile3 end,
    case when companylocation.Phone3 is null then '' else companylocation.Phone3 end,
    case when companylocation.Phone4 is null then '' else companylocation.Phone4 end,
    case when Businessinfo.KeyOfficialPhone2 is null then '' else Businessinfo.KeyOfficialPhone2 end SEPARATOR ', ') as telephone

我得到以下结果。

3   NULL
3   9876542344NULL1800234234
3   9876542344NULL
3   NULL, NULL2663822
3   8952939102NULL
3   9811164837NULL
4   NULL2461999
5   NULL
6   9910270032NULL
6   9540828102NULL
8   9440601141NULL
9   9414131222NULL
10  9842731310NULL2252608

但是当我尝试以下查询时

   GROUP_concat(DISTINCT concat(case when (length(companylocation.Mobile) > 0 AND (companylocation.Mobile=NULL)) then concat(companylocation.Mobile, ', ') else concat(companylocation.Mobile) end), 
    concat(case when length(companylocation.Mobile2) > 0 then concat(companylocation.Mobile2, ', ') else concat(companylocation.Mobile2) end),
    concat(case when length(companylocation.Mobile3) > 0 then concat(companylocation.Mobile3, ', ') else concat(companylocation.Mobile3) end),
    concat(case when length(companylocation.Phone3) > 0 then concat(companylocation.Phone3, ', ') else concat(companylocation.Phone3) end),
    concat(case when length(companylocation.Phone4) > 0 then concat(companylocation.Phone4, ', ') else concat(companylocation.Phone4) end),
    concat(case when length(Businessinfo.KeyOfficialPhone2) > 0 then concat(Businessinfo.KeyOfficialPhone2, ', ') else concat(Businessinfo.KeyOfficialPhone2) end) SEPARATOR ', ' ) as telephone

我得到所有“空”结果。

我想要的是如下:

3   9876542344, 1800234234
10  9842731310, 2252608

有人可以帮我解决这个问题吗。

1 个答案:

答案 0 :(得分:0)

您需要在group_concat()的查询中使用group by。我怀疑你想要这样的东西group by

GROUP_concat(DISTINCT
             concat_ws(', ', companylocation.Mobile, companylocation.Mobile2, 
                       companylocation.Mobile3, companylocation.Phone3, companylocation.Phone4, 
                       Businessinfo.KeyOfficialPhone2)
             separator ', ')