Search code examples
mysqlgroup-concat

MySQL Group Concat Single Column NULL


I have a column that i am looking to retrieve all matches of in one row. I am querying other data as well. Currently i am using group_concat. This has worked great until now. Sometimes there are potential NULL values in this column and this has been preventing anything from being returned.

i have tried various other solutions posted here without success.

CREATE TABLE table1 (
id mediumint(9) NOT NULL AUTO_INCREMENT,
item_num mediumint(9) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE table2 (
id mediumint(9) NOT NULL AUTO_INCREMENT,
oneid mediumint(9) NOT NULL,
item_desc varchar(16) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

SELECT item_num, GROUP_CONCAT(item_desc) AS alldesc FROM table1 LEFT JOIN table2 ON table1.id = table2.oneid

So basically, there can be several item descripotions that may be NULL; they will be in no particular order either. So i am seeking a list with a placeholder when NULLs arise.


Solution

  • Does this work for you(use description as empty string when it is NULL)?

    SELECT item_num, 
           REPLACE(GROUP_CONCAT(IFNULL(item_desc,' ')), ', ,', ',') AS alldesc 
    FROM table1 
    LEFT JOIN table2 
    ON table1.id = table2.oneid