MariaDB:无法在依赖子查询中引用父表--在MySQL中相同查询有效

o4hqfura  于 11个月前  发布在  Mysql
关注(0)|答案(1)|浏览(82)

在MySQL 8中运行下面的查询会产生如下所示的行:
| data |
| ------------ |
| AC/DC "AC/DC"}]} |
| “接受”}]} "Accept"}]} |
但是,在MariaDB 10.11.2中运行相同的查询会出现以下错误:

[42S22][1054] (conn=27) Unknown column 'Album.ArtistId' in 'where clause'

有没有人碰巧知道为什么会这样,如果有一种方法来解决它?
谢谢你。

DBFiddle链接:

with Artist(ArtistId, Name) as (
    select 1 as ArtistId, 'AC/DC' as Name
    union all
    select 2 as ArtistId, 'Accept' as Name
), Album(AlbumId, Title, ArtistId) as (
    select 1 as AlbumId, 'For Those About To Rock We Salute You' as Title, 1 as ArtistId
    union all
    select 2 as AlbumId, 'Balls to the Wall' as Title, 2 as ArtistId
)

select
    json_object(
            'Artist',
            (
                select
                    json_arrayagg(j)
                from
                    (
                        select
                            json_object('Name', `Name`) as `j`
                        from
                            (
                                select
                                    `Artist`.*
                                from
                                    `Artist`
                                where
                                        -- !!! ERROR HAPPENS HERE IN MARIADB !!!
                                        `Album`.`ArtistId` = `Artist`.`ArtistId`
                            ) as `Artist`
                    ) as `j`
            )
        ) as data
from
    (
        select
            `Album`.*
        from
            `Album`
    ) as `Album`;
xoefb8l8

xoefb8l81#

我不知道为什么它不起作用,但这里是你如何实现你想要的,一个小的变化。
你需要在与json_arrayagg相同的级别上执行join,然后它就可以工作了:

with Artist(ArtistId, Name) as (
    select 1 as ArtistId, 'AC/DC' as Name
    union all
    select 2 as ArtistId, 'Accept' as Name
), Album(AlbumId, Title, ArtistId) as (
    select 1 as AlbumId, 'For Those About To Rock We Salute You' as Title, 1 as ArtistId
    union all
    select 2 as AlbumId, 'Balls to the Wall' as Title, 2 as ArtistId
)
select
    json_object(
        'Artist',
        (
            select
                json_arrayagg(`ArtistJson`.`j`)
            from
            (
                select
                    json_object('Name', `Name`) as `j`,
                    `ArtistAlias`.`ArtistId` -- Return the join column here
                from
                (
                    select
                        `Artist`.*
                    from
                        `Artist`
                ) as `ArtistAlias`
            ) as `ArtistJson`
            -- So that you can use it here
            where `AlbumAlias`.`ArtistId` = `ArtistJson`.`ArtistId` 
        )
    ) as data
from
(
    select
        `Album`.*
    from
        `Album`
    
) as `AlbumAlias`;

相关问题