How to prevent GROUP_CONCAT from creating a result when no input data is present?

Der Hochstapler picture Der Hochstapler · Sep 6, 2010 · Viewed 9.5k times · Source

Given the following MySQL query:

SELECT
  `show`.`id`
  , GROUP_CONCAT( `showClips`.`clipId` ORDER BY `position` ASC ) AS 'playlist'
FROM
  `show`
  INNER JOIN
    `showClips`
      ON
        ( `show`.`id` = `showClips`.`showId` )
;

I want to retrieve a list of all "shows" from the database, including the ids of contained "clips".

This works fine, as long as there are entries in the show table. For this problem, let's assume all tables are completely empty.

GROUP_CONCAT will return NULL and thus forcing a row into the result (which contains only NULL values).

My application will then think that one show/result exists. But that result will be invalid. This can of course be checked, but I feel like this could (and should) be prevented in the query already.

Answer

Daniel Vassallo picture Daniel Vassallo · Sep 6, 2010

You should simply add a GROUP BY at the end.

Test case:

CREATE TABLE `show` (id int);
CREATE TABLE `showClips` (clipId int, showId int, position int);

SELECT 
   `show`.`id`,
   GROUP_CONCAT( `showClips`.`clipId` ORDER BY `position` ASC ) AS 'playlist'
FROM  `show`
INNER JOIN `showClips` ON ( `show`.`id` = `showClips`.`showId` )
GROUP BY `show`.`id`;

Empty set (0.00 sec)