Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 954
Oliver Salzburg Avatar asked Sep 06 '10 15:09

Oliver Salzburg


People also ask

Is there a limit to Group_concat?

Show activity on this post. I'm using GROUP_CONCAT() in a MySQL query to convert multiple rows into a single string. However, the maximum length of the result of this function is 1024 characters.

Is Group_concat slow?

So, the GROUP_CONCAT is an additional work for the MySQL involving strings, so you should expect some slow down, but rest assured it will not kill the performance of the MySQL.

What does Group_concat do in SQL?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.


1 Answers

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) 
like image 168
Daniel Vassallo Avatar answered Sep 28 '22 07:09

Daniel Vassallo