How to prevent GROUP_CONCAT from creating a result when no input data is present?
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开发者_如何学Python.
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)
Add group by show
.id
, then result will be correct for empty tables:
create table emptyt(id int, name varchar(20));
select id, group_concat(name) from emptyt
result:
NULL, NULL
query with group by
select id, group_concat(name) from emptyt
group by Id
result:
empty dataset
精彩评论