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

后端 未结 4 1573
故里飘歌
故里飘歌 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:41

    you're comparing apples to oranges when comparing the final query to the others as the LEVEL is isolated in that to the 1-row dual table.

    lets consider this query:

     select id, level as lvl
       from a
    connect by level <= 2
      order by id, level
    

    what that is saying is, start with the table set (select * From a). then, for each row returned connect this row to the prior row. as you have not defined a join in the connect by, this is in effect a Cartesian join, so when you have 3 rows of (1,2,3) 1 joins to 2, 1->3, 2->1, 2->3, 3->1 and 3->2 and they also join to themselves 1->1,2->2 and 3->3. these joins are level=2. so we have 9 joins there, which is why you get 12 rows (3 original "level 1" rows plus the Cartesian set).

    so the number of rows output = rowcount + (rowcount^2)

    in the last query you are isolating level to this

    select level  as lvl
               from dual
            connect by level  <= 2
    

    which of course returns 2 rows. this is then cartesianed to the original 3 rows, giving 6 rows as output.

提交回复
热议问题