Why does CONNECT BY LEVEL on a table return extra rows?

后端 未结 4 1601
故里飘歌
故里飘歌 2020-12-30 05:19

Using CONNECT BY LEVEL seems to return too many rows when performed on a table. What is the logic behind what\'s happening?

Assuming the following table:

<         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 05:57

    In the first query, you connect by just the level. So if level <= 1, you get each of the records 1 time. If level <= 2, then you get each level 1 time (for level 1) + N times (where N is the number of records in the table). It is like you are cross joining, because you're just picking all records from the table until the level is reached, without having other conditions to limit the result. For level <= 3, this is done again for each of those results.

    So for 3 records:

    • Lvl 1: 3 record (all having level 1)
    • Lvl 2: 3 records having level 1 + 3*3 records having level 2 = 12
    • Lvl 3: 3 + 3*3 + 3*3*3 = 39 (indeed, 13 records each).
    • Lvl 4: starting to see a pattern? :)

    It's not really a cross join. A cross join would only return those records that have level 2 in this query result, while with this connect by, you get the records having level 1 as well as the records having level 2, thus resulting in 3 + 3*3 instead of just 3*3 record.

提交回复
热议问题