为什么“别名X与同名语句中的别名冲突”使用别名CTE而不使用别名表?

时间:2017-04-11 19:05:30

标签: firebird firebird2.5

我想知道为什么以下语句至少会在Win32 Firebird WI-V2.5.7.27050和WI-V2.5.2.26540版本中导致此错误。

 Dynamic SQL Error SQL error code = -204 alias TRIPLEDIGITS conflicts with an alias in the same statement

解决SQL语句中的许多错误,上面的错误并不表示导致错误的行,但是有一些小问题,我发现标有注释的行会导致它。

查询一个CTE未压缩且具有相同的CTE别名:

with 
  recursive 
  tripledigits(n) as (        
    select 0
    from rdb$database
    union all
    select tripledigits.n + 1
    from tripledigits
    where tripledigits.n < 999
  ),
  sextupledigits(n) as (
    select tripledigits.n 
          + tripledigits000.n * 1000
    from tripledigits
    cross join tripledigits tripledigits000 -- causes "Dynamic SQL Error SQL error code = -204 alias TRIPLEDIGITS conflicts with an alias in the same statement"
    order by tripledigits.n 
          + tripledigits000.n * 1000
  )
select sextupledigits.n 
from sextupledigits
order by sextupledigits.n

将失败的查询从sextupledigits CTE移到主查询中时,它也会失败:

with 
  recursive 
  tripledigits(n) as (        
    select 0
    from rdb$database
    union all
    select tripledigits.n + 1
    from tripledigits
    where tripledigits.n < 999
  )
select tripledigits.n 
      + tripledigits000.n * 1000
from tripledigits
cross join tripledigits tripledigits000 -- causes "Dynamic SQL Error SQL error code = -204 alias TRIPLEDIGITS conflicts with an alias in the same statement"
order by tripledigits.n 
      + tripledigits000.n * 1000

使用以下方法使用非混淆表并使用相同的表别名:

select rdb$database.rdb$relation_id  + rd.rdb$relation_id * 1000
from rdb$database
cross join rdb$database rd

为什么我的基于CTE的查询会抛出错误?

我至少知道两种解决方法(见下文),但出于文档目的和后人的目的,我想回答一下这个问题。

解决方法1:CTE使用的别名

with 
  recursive
  tripledigits(n) as (        
    select 0
    from rdb$database
    union all
    select tripledigits.n + 1
    from tripledigits
    where tripledigits.n < 999
  ),
  sextupledigits(n) as (
    select tripledigitsBare.n 
          + tripledigits000.n * 1000
    from tripledigits tripledigitsBare
    cross join tripledigits tripledigits000
    order by tripledigitsBare.n 
          + tripledigits000.n * 1000
  )
select sextupledigits.n 
from sextupledigits
order by sextupledigits.n

解决方法2:使用中间CTE

with 
  recursive
  tripledigits(n) as (        
    select 0
    from rdb$database
    union all
    select tripledigits.n + 1
    from tripledigits
    where tripledigits.n < 999
  ),
  tripledigits000(n) as (
    select tripledigits.n * 1000
    from tripledigits
  ),
  sextupledigits(n) as (
    select tripledigits.n 
          + tripledigits000.n
    from tripledigits
    cross join tripledigits000
    order by tripledigits.n 
          + tripledigits000.n
  )
select sextupledigits.n 
from sextupledigits
order by sextupledigits.n 

我已在Firebird跟踪器中将其报告为CORE-5519

0 个答案:

没有答案