分页时,行数不适用于重复列

时间:2015-04-08 09:29:11

标签: oracle pagination

代码如下所示,多个嵌套查询:

 select *
        from
      (select employee_id,employee_id
         from employees) a
       where rownum <= 5
      )
       where rnum >= 10

如果我在select中给出重复的列,那么'#34;列模糊定义&#34;错误。

2 个答案:

答案 0 :(得分:3)

  

employee_id,employee_id,rownum rnum

  • 首先,您的查询不正确,因为模糊地定义了列。它将抛出ORA-00918: column ambiguously defined

您必须使用正确的 ALIAS 来避免错误。例如,

SELECT departments.department_id AS "dept_id", 
        employees.department_id  AS "emp_Dept_id" 
FROM...
  • 其次,它根本不是分页查询。由于没有 ORDER BY 子句,因此您需要选择随机行。你没有订购行。
  

其中rownum&lt; = 5

     

其中rnum&gt; = 10

  • 最后,当你在内部查询中只获取了5行时,你怎么能尝试获取超过10的行? 总是返回零行

分页数据的正确方法是:

SQL> SELECT empno
  2  FROM   (SELECT empno, rownum AS rnum
  3          FROM   (SELECT empno
  4                  FROM   emp
  5                  ORDER BY sal)
  6          WHERE rownum <= 8)
  7  WHERE  rnum >= 5;

     EMPNO
----------
      7654
      7934
      7844
      7499

SQL>

答案 1 :(得分:1)

  

当您提供a.*时,表示您尝试在不允许的表中引用具有相同名称的两列。表中的列名称是唯一的

     

所以select employee_id,employee_id from employees不是问题

     

但是

     

select a.* from (select employee_id,employee_id from employees)a是个问题

     

the sqlfiddle here

此外,如果您想在查询中使用10到15的记录,请使用如下所示

  select * from 
     (select a.*,Rownum rnum from 
     (select employee_id as emp_id1,employee_id as emp_id2 
         from employees order by 1) 
      a where rownum <= 15 ) where rnum >= 10 

EDIT1: - 如果需要重复列,请使用如下所示

  with emp1 as (select employee_id from employees),
  emp2 as (select * from 
          (select a.*,rownum rnum from emp1 a order by 1)   
           where rownum <=15)
  select b.*,c.*
  from emp1 b,emp2 c
  where b.employee_id=c.employee_id
  and c.rnum >=10