25

给定以下 MySQL 查询:

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

我想从数据库中检索所有“节目”的列表,包括包含的“剪辑”的 ID。

这工作正常,只要表中有条目show。对于这个问题,我们假设所有表都是空的。

GROUP_CONCAT将返回NULL并因此强制将一行放入结果(仅包含NULL值)。

然后我的应用程序会认为存在一个节目/结果。但那个结果将是无效的。这当然可以检查,但我觉得这可以(并且应该)在查询中被阻止。

4

2 回答 2

48

您应该简单地GROUP BY在末尾添加一个。

测试用例:

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)
于 2010-09-06T15:30:45.533 回答
11

添加分组依据showid,那么结果对于空表将是正确的:

创建表emptyt(id int,名称varchar(20));

   select id, group_concat(name) from emptyt

结果:

 NULL, NULL

分组查询

 select id, group_concat(name) from emptyt
 group by Id

结果:

空数据集

于 2010-09-06T15:30:09.537 回答