具有多个基本案例的递归SQL

时间:2017-08-28 16:30:15

标签: mysql sql sqlite

public Something setId(Long id) {
    if (id != null) 
        this.id = id;
    else 
        this.id = DEFAULT_ID; 
    return this;
}

将返回4999行数据。这对我来说很有意义,因为基本情况都是

create table flight_costs as
  with
    costs(day, curr, prev) as (
      select 1, 20, 0 union
      select 1.5, 30, 20 UNION
      select 3, 40, 30 UNION
      select day + 1, (curr + prev)/2 + ((day + 1) % 7) * 5, curr from costs
      where day < 2500 and day > 1
  )
  select day as day, curr as price from costs;

但是,我不明白为什么

select 1.5, 30, 20 UNION
select 3, 40, 30 UNION

只会返回2500行

create table flight_costs as
  with
    costs(day, curr, prev) as (
      select 1, 20, 0 union
      select 2, 30, 20 UNION
      select 3, 40, 30 UNION
      select day + 1, (curr + prev)/2 + ((day + 1) % 7) * 5, curr from costs
      where day < 2500 and day > 1
  )
  select day as day, curr as price from costs;

应循环播放,并返回

day 
1
2
3
3
4
4
5
5
6....

而不是

day
1
2
3
4
5
6....

1 个答案:

答案 0 :(得分:0)

我的猜测是UNION正在消除重复。

例如:select day + 1, (curr + prev)/2 + ((day + 1) % 7) * 5, curr from costs (2, 30, 20)会产生(3, 40, 30);这将产生与从递归调用的初始(3,40,30)产生的所有内容完全相同的结果。

...但这确实让我想知道为什么第一个查询只有4999行;它应该从最初的1行有2500,从最初的1.5行有2499,从最初的3行有2498。 3行和1行的后代可能会收敛,但由于这显然不是立即的,所以总数应该仍然超过4999。

您可以使用UNION ALL包含重复项。