当不存在输入数据时,如何防止 GROUP_CONCAT 创建结果?
给出以下 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
值)。
然后我的应用程序将认为存在一个显示/结果。但这个结果将是无效的。这当然可以检查,但我觉得这可以(并且应该)在查询中被阻止。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需在末尾添加一个
GROUP BY
即可。测试用例:
You should simply add a
GROUP BY
at the end.Test case:
添加 group by
show
.id
,则空表的结果将是正确的:create table emptyt(id int, name varchar(20));
结果:
按结果分组查询
:
空数据集
Add group by
show
.id
, then result will be correct for empty tables:create table emptyt(id int, name varchar(20));
result:
query with group by
result:
empty dataset