我有以下查询:
select * from
(select rownum rnum, p.* from
(select DEPARTMENTS.DEPARTMENT_ID,
DEPARTMENTS.DEPARTMENT_NAME,
DEPARTMENTS.MANAGER_ID,
EMPLOYEES.EMPLOYEE_ID,
EMPLOYEES.FIRST_NAME,
EMPLOYEES.LAST_NAME,
EMPLOYEES.MANAGER_ID,
EMPLOYEES.DEPARTMENT_ID,
EMPLOYEES.DETAILS
from HR.EMPLOYEES
INNER JOIN HR.DEPARTMENTS on
HR.DEPARTMENTS.DEPARTMENT_ID=EMPLOYEES.DEPARTMENT_ID
where EMPLOYEES.EMPLOYEE_ID >= 1) p
where rownum <= 4)
where rnum >= 2
这给了我以下错误:
错误SQL:ORA-00918:列定义不明确 00918. 00000-“列定义不明确”
如果字段的名称不同,则没有错误。例如,此查询是正确的:
select * from
(select rownum rnum, p.* from
(select DEPARTMENTS.DEPARTMENT_ID,
DEPARTMENTS.DEPARTMENT_NAME,
DEPARTMENTS.MANAGER_ID,
EMPLOYEES.EMPLOYEE_ID,
EMPLOYEES.FIRST_NAME,
EMPLOYEES.LAST_NAME,
EMPLOYEES.DETAILS
from HR.EMPLOYEES
INNER JOIN HR.DEPARTMENTS on
HR.DEPARTMENTS.DEPARTMENT_ID=EMPLOYEES.DEPARTMENT_ID
where EMPLOYEES.EMPLOYEE_ID >= 1) p
where rownum <= 4)
where rnum >= 2
使用分页进行内部联接以及来自具有相同名称的不同表中的字段的正确语法是什么?如何避免在第一次查询中出现ORA-00918错误?
我正在使用Oracle 11g。
答案 0 :(得分:1)
在内部查询中使用列别名 例如
-- outer query omitted, table aliases and column aliases added
select rownum rnum, p.*
from (
select
D.DEPARTMENT_ID did
, D.DEPARTMENT_NAME dname
, D.MANAGER_ID dmgr
, E.EMPLOYEE_ID eid
, E.FIRST_NAME efname
, E.LAST_NAME elname
, E.MANAGER_ID emgr
, E.DEPARTMENT_ID edept
-- , E.DETAILS
from HR.EMPLOYEES E
INNER JOIN HR.DEPARTMENTS D on D.DEPARTMENT_ID = E.DEPARTMENT_ID
where E.EMPLOYEE_ID >= 1 ) p
;
-- result
RNUM DID DNAME DMGR EID EFNAME ELNAME EMGR EDEPT
1 10 Administration 200 200 Jennifer Whalen 101 10
2 20 Marketing 201 201 Michael Hartstein 100 20
3 20 Marketing 201 202 Pat Fay 201 20
4 30 Purchasing 114 114 Den Raphaely 100 30
5 30 Purchasing 114 115 Alexander Khoo 114 30
6 30 Purchasing 114 116 Shelli Baida 114 30
7 30 Purchasing 114 117 Sigal Tobias 114 30
8 30 Purchasing 114 118 Guy Himuro 114 30
9 30 Purchasing 114 119 Karen Colmenares 114 30
...
MANAGER_ID和DEPARTMENT_ID列(不带别名)导致您描述的错误(删除注释以获取错误消息):
select rownum rnum, p.*
from (
select
D.DEPARTMENT_ID
, D.DEPARTMENT_NAME
--, D.MANAGER_ID
, E.EMPLOYEE_ID
, E.FIRST_NAME
, E.LAST_NAME
, E.MANAGER_ID
--, E.DEPARTMENT_ID
from HR.EMPLOYEES E
INNER JOIN HR.DEPARTMENTS D on D.DEPARTMENT_ID = E.DEPARTMENT_ID
where E.EMPLOYEE_ID >= 1 ) p
;
-- ORA-00918: column ambiguously defined