MariaDB自定义函数调用JSON_ARRAYAGG报1111错误的原因?
问题:MariaDB函数调用报ERROR 1111 (HY000): Invalid use of group function
我创建了一个返回JSON_OBJECT的MariaDB函数jsontree,函数代码如下:
DROP FUNCTION IF EXISTS jsontree; CREATE FUNCTION jsontree (user_id VARCHAR(36)) RETURNS LONGTEXT RETURN ( SELECT JSON_OBJECT( '_item_type', JSON_UNQUOTE("model"), '_path', JSON_UNQUOTE("organization"), '_title', JSON_UNQUOTE("Organizations"), 'user', ( SELECT JSON_OBJECT( '_item_type', JSON_UNQUOTE("node"), '_path', JSON_UNQUOTE("organizations.user"), '_title', JSON_UNQUOTE("Users"), '_table', JSON_UNQUOTE("user"), 'children', JSON_ARRAYAGG( JSON_OBJECT( 'user.createdAt', user.createdAt, 'user.createdBy', user.createdBy, 'user.number', user.number, 'user.name', user.name, 'user.description', user.description, 'user.user_id', user.user_id, 'user.organization_id', user.organization_id, 'user.job_id', user.job_id, 'user.password', user.password, 'organization', ( SELECT JSON_OBJECT( '_item_type', JSON_UNQUOTE("node"), '_path', JSON_UNQUOTE("organizations.user.organization"), '_title', JSON_UNQUOTE("Organizations"), '_table', JSON_UNQUOTE("organization"), 'children', JSON_ARRAYAGG( JSON_OBJECT( 'organization.id', organization_table.id, 'organization.createdAt', organization_table.createdAt, 'organization.createdBy', organization_table.createdBy, 'organization.number', organization_table.number, 'organization.name', organization_table.name, 'organization.description', organization_table.description, 'organization.user_id', organization_table.user_id, 'organization.organization_id', organization_table.organization_id ) ) ) FROM organization organization_table INNER JOIN user user_join ON organization_table.user_id = user_join.id WHERE organization_table.user_id = user.id ) ) ) ) FROM user where user.id = user_id ) ) ); SELECT jsontree ('4841aa13-01a6-11ed-8fb9-da2c4dfd0e4f');
单独执行函数内的SELECT语句可得到预期的JSON_OBJECT,但调用该函数时持续报错:ERROR 1111 (HY000): Invalid use of group function,请问该错误产生的原因是什么?
错误原因分析
- 核心问题是函数内嵌套的子查询中使用了聚合函数
JSON_ARRAYAGG,但未显式指定GROUP BY子句。 - 单独执行内部SELECT语句时,MariaDB会在特定场景下(比如WHERE条件过滤出单条记录)隐式处理分组逻辑,默认将整个结果集作为一个分组。但在自定义函数的执行环境中,这种隐式分组规则不生效,数据库无法确定聚合函数的分组范围,因此抛出"Invalid use of group function"错误。
- 具体涉及两处
JSON_ARRAYAGG的使用:- 外层针对
user表的子查询中,'children', JSON_ARRAYAGG(...)部分缺少GROUP BY; - 内层嵌套的
organization子查询中,'children', JSON_ARRAYAGG(...)部分同样未指定GROUP BY。
- 外层针对
修复方案
在两处使用JSON_ARRAYAGG的子查询中添加对应的GROUP BY子句:
- 针对
user表的子查询末尾添加GROUP BY user.id; - 针对
organization_table的子查询末尾添加GROUP BY organization_table.user_id(可根据实际业务需求调整分组字段)。
内容的提问来源于stack exchange,提问作者Bumblebee
相关产品推荐
相关产品推荐

