mysql 当查询中有多个CTE时具有单个递归CTE

uemypmqf  于 2023-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(141)

我不确定以前是否有人问过这个问题,但我在不同的论坛上搜索过,没有找到确切的答案。我们是否应该总是将单词RECURSIVE初始化为第一个CTE(即使它不是递归CTE),以便整个查询运行?
示例查询:

-- initalising some data
with temp_cte1 as (
  select
  100 as id,
  'test' as name,
  30000 as salary,
  date('2011-10-28') as start_date,
  date('2011-11-30') as end_date
),

-- this cte is to get all the dates between the start and end dates
temp_cte2 as (
  select
    id,
    start_date as curr_day,
    end_date
  from temp_cte1
  union all
  select 
    id,
    DATE_ADD(curr_day, INTERVAL 1 DAY) as curr_day,
    end_date
  from temp_cte2
  where curr_day < end_date
),

-- this cte is filter out specific dates from tempcte2
temp_cte3 as (
  select
    id,
    count(*) as pay_days
  from temp_cte2
  where DAY(curr_day) in (1, 15)
  group by id
)

select 
  d.id,
  d.name,
  d.salary,
  d.start_date,
  d.end_date,
  f.pay_days
from temp_cte1 d
left join temp_cte3 f
on d.id = f.id

上面的查询抛出表temp_cte2不存在的错误:错误响应:错误代码:1146.表'final.temp_cte2'不存在

-- initalising some data
with recursive temp_cte1 as (
  select
  100 as id,
  'test' as name,
  30000 as salary,
  date('2011-10-28') as start_date,
  date('2011-11-30') as end_date
),

-- this cte is to get all the dates between the start and end dates
temp_cte2 as (
  select
    id,
    start_date as curr_day,
    end_date
  from temp_cte1
  union all
  select 
    id,
    DATE_ADD(curr_day, INTERVAL 1 DAY) as curr_day,
    end_date
  from temp_cte2
  where curr_day < end_date
),

-- this cte is filter out specific dates from tempcte2
temp_cte3 as (
  select
    id,
    count(*) as pay_days
  from temp_cte2
  where DAY(curr_day) in (1, 15)
  group by id
)

select 
  d.id,
  d.name,
  d.salary,
  d.start_date,
  d.end_date,
  f.pay_days
from temp_cte1 d
left join temp_cte3 f
on d.id = f.id

但是如果在起始CTE中使用关键字RECURSIVE进行初始化(即使CTE不是递归的),查询也可以正常运行。有人能解释一下为什么我应该在顶部使用关键字RECURSIVE初始化递归CTE吗?
我想知道为什么我们必须在第一个cte中使用关键字RECURSIVE。

v1l68za4

v1l68za41#

关键字WITH和RECURSIVE与所有CTE相关联,而不仅仅是列表中的第一个CTE。RECURSIVE只是意味着CTE中可能存在递归逻辑,而不是任何一个特定CTE(或所有CTE)都是递归的

相关问题