对oracle伪列rownum产生机制的理解

    技术2022-05-13  51

    rownum列数据按下面的5步生成:

      1.Oracle executes your query.

      2.Oracle fetches the first row and calls it row number 1.

        翻译:Oracle取出第一条数据,并给字段rownum赋值1

      3.Have we gotten past row number meets the criteria? If no, then Oracle discards the row, If yes, then Oracle return the row.

        翻译:我们已经得到符合标准的行号?如果是,返回该行,如果不是,丢弃。

      4.Oracle fetches the next row and advances the row number (to 2, and then to 3, and then to 4, and so forth).

        翻译:Oracle取出下一条数据,并给字段rownum赋递增值,比如2,3,4等。

      5.Go to step 3.

     

      为什么不能对rownum">"?

      假设存在表emp,其共col1,col2两列,多行数据,执行sql语句:select * from emp where rownum > 3.表数据如下:

       列名  col1  col2  col3  rownum

       列值  001    a     b

             002    a     b

             003    a     b

             004    a     b

             005    a     b

                  ...

                  ...

       步骤1中,oracle按非rownum相关的条件查询出所有记录

         列名  col1  col2  col3  rownum

              列值  001    a     b

               002    a     b

               003    a     b

               004    a     b

               005    a     b

                  ...

                  ...

       步骤2中,oracle取出第一条数据,并给其rownum列赋值1,如下

         列名  col1  col2  col3  rownum

     

         列值  001    a     b         1

               002    a     b

               003    a     b

               004    a     b

               005    a     b

       步骤3中,对rownum已有值的列:001 a  b   1进行判断,判断条件是rownum > 3,结果为no,该行丢弃。

     

         列名  col1  col2  col3  rownum

              列值  002    a     b

               003    a     b

               004    a     b

               005    a     b

                    ...

                    ...

       步骤4中,对行002    a     b的rownum赋值为1,因为第三步已经丢弃了行001    a     b,如果没有丢弃,应该对002    a     b的rownum赋值为2

         列名  col1  col2  col3  rownum

              列值  002    a     b      1

               003    a     b

               004    a     b

               005    a     b

                     ...

                     ...

     

              

        步骤5又跳入步骤3,仍进行rownum > 3的判断,仍然丢弃数据,到第四步新行的rownum仍然赋值为1,如此循环下去,select * from emp where rownum > 3查询结果为空。

       

     

           


    最新回复(0)