4

There is a sample schema in here: http://sqlfiddle.com/#!2/c0723a/2

query is select id,group_concat(val) from test group by id

result is

ID GROUP_CONCAT(VAL)
1 ,64,66,,203,214,204

I wanted to concat val field without a comma for empty records like this

ID GROUP_CONCAT(VAL)
1 64,66,203,214,204

BenMorel
  • 34,448
  • 50
  • 182
  • 322
zgormez
  • 429
  • 5
  • 9

3 Answers3

5

Simply use Replace

select id,replace(group_concat(val),',,',',') from test group by id

Or you can use IF

select id,group_concat(if(val ='',null, val)) from test group by id

Or You can use NULLIF

select id,group_concat(Nullif(val,'')) from test group by id

Fiddle Demo

Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
4
SELECT id, GROUP_CONCAT(val) FROM test 
WHERE val is not null AND val <> '' 
GROUP BY id
StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • this should be the correct answer. it's simple and more accurate – John Feb 01 '17 at 02:53
  • Yes, this answer is correct, if there is no any other field in the query. But, when i want to select the records even if the val field is null it is not correct – zgormez Feb 27 '17 at 13:43
1

Add an IF check, GROUP_CONCAT will skip the NULL value.

select id, group_concat(IF(val = '', null, val)) from test group by id

THE SQLFIDDLE.

xdazz
  • 158,678
  • 38
  • 247
  • 274