MariaDB / MySQL CTE原始SQL不明确错误

t1rydlwq  于 2022-11-08  发布在  Mysql
关注(0)|答案(1)|浏览(154)

我有一个RAWSQL查询

with 
    group as (
     select * from groups where id = ?
    ),
    attributes as (
     select JSON_ARRAYAGG(
     JSON_OBJECT('id', a.id,'name', a.name ))
     from attributes a
     join groups g on g.id = ?
     join attribute_group ag on ag.group_id = g.id
     and ag.attribute_id = a.id
    ),
    templates as (
     select JSON_ARRAYAGG(
     JSON_OBJECT('id', t.id,'name', t.name))
     from templates t
     join groups g on g.id = ?
     join group_template gt on gt.group_id = g.id
     and gt.template_id = t.id
    )

    select *, 
    (select cast(count(*) as char) from attribute_group where group_id = ? ) groups_count,
    (select * from groups) groups,
    (select cast(count(*) as char) from group_template where group_id = ? ) templates_count,
    from group

我有此错误

Query 1 ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'group as (
8aqjt8rx

8aqjt8rx1#

该文档建议不要使用保留字,如groupgroups。它们是保留字符,只应用于GROUP BY语句:
组(R)
分组(R);在8.0.1中添加(保留)
组(R);在8.0.2中添加(保留)
除此之外,我还注意到一些语法错误:
1.如果您有一个名为GROUP的表(看起来确实如此),您可以使用反勾号或双引号“”来转义保留字(即'group',“group”)。
1.删除templates_count,后面的逗号,
1.将?替换为有效的id列值(我在下面使用了1)。
就像这样:

with 
    `group` as (
     select * from `groups` where id = 1
    ),
    attributes as (
     select JSON_ARRAYAGG(
     JSON_OBJECT('id', a.id,'name', a.name ))
     from attributes a
     join `groups` g on g.id = 1
     join attribute_group ag on ag.group_id = g.id
     and ag.attribute_id = a.id
    ),
    templates as (
     select JSON_ARRAYAGG(
     JSON_OBJECT('id', t.id,'name', t.name))
     from templates t
     join `groups` g on g.id = 1
     join group_template gt on gt.group_id = g.id
     and gt.template_id = t.id
    )

    select *, 
    (select cast(count(*) as char) from attribute_group where group_id = 1 ) groups_count,
    (select * from `groups`)  `groups`,
    (select cast(count(*) as char) from group_template where group_id = 1 ) templates_count
    from `group`

相关问题