简述Oracle的rownum原理

rownum背后的机制:

  1. Oracle executes your query.
  2. Oracle fetches the first row and calls it row number 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).
  5. Go to step 3.

具体流程如下:(帮助大家理解)

  1. 先按照where中除了rownum以外的其他条件筛选出结果并生成结果集 。
  2. 给第一步生成的结果集加上rownum伪列。
  3. 按照rownum的条件进一步限制,分两种情况:
    3.1 如果第一条记录不符合rownum的限制条件,则把该记录丢弃,且下一条记录的rownum还是从1开始重新计数。
    3.2 如果第一条记录符合rownum的限制条件,则把该记录筛选出来,且下一条记录的rownum从2开始,并重新进入第三步进行判断。

举个简单的例子,正确的写法:

/* 
    1.第一条记录的rownum为1,满足rownum <= 5 的限制条件,把第一条记录筛选出来
    2.第二条

你可能感兴趣的:(编程开发,DB,oracle,rownum原理)