1

我有两张桌子——员工和经理。一位经理有许多员工。我想使用 CONNECT BY 和 GROUP BY 命令在父子关系中显示它。

EMPLOYEE 表的结构:

CREATE TABLE employee (
  employee_id INTEGER,
  manager_id INTEGER,
  first_name VARCHAR2(10) NOT NULL,
  last_name VARCHAR2(10) NOT NULL
);

经理表的结构:

CREATE TABLE manager(
  manager_id INTEGER NOT NULL,
  manager_dept VARCHAR2(20) NOT NULL,
  first_name VARCHAR2(30) NOT NULL,
  last_name  VARCHAR2(30) NOT NULL
);

我写了这个查询:

SELECT E.EMPLOYEE_ID, M.MANAGER_ID, E.FIRST_NAME, E.LAST_NAME, CONNECT_BY_ISLEAF, CONNECT_BY_ISCYCLE
FROM EMPLOYEE E
LEFT OUTER JOIN MANAGER M
ON E.MANAGER_ID=M.MANAGER_ID
connect by NOCYCLE m.manager_id=prior e.employee_id
GROUP BY manager_id;

它给出了这个错误:

ORA-00918: column ambiguously defined
00918. 00000 -  "column ambiguously defined"
Error at Line: 6 Column: 10

这个 group by 子句有什么问题?

4

2 回答 2

0

GROUP BY 中的 manager_id 列不明确 - 它可能是员工表的 manager_id,也可能是经理表的 manager_id。

您还需要将剩余的列添加到您的 GROUP BY。然后完整的查询变为:

SELECT 
  E.EMPLOYEE_ID, M.MANAGER_ID, E.FIRST_NAME, 
  E.LAST_NAME, CONNECT_BY_ISLEAF, CONNECT_BY_ISCYCLE
FROM EMPLOYEE E
LEFT OUTER JOIN MANAGER M
  ON E.MANAGER_ID=M.MANAGER_ID
connect by NOCYCLE m.manager_id=prior e.employee_id
GROUP BY 
  E.EMPLOYEE_ID, M.MANAGER_ID, E.FIRST_NAME, 
  E.LAST_NAME, CONNECT_BY_ISLEAF, CONNECT_BY_ISCYCLE;
于 2013-12-16T12:00:38.690 回答
0

你得到column ambiguously defined是因为 oracle 无法确定哪个表的 manager_id 应该用于 group by,因为你没有指定它。正确的查询是:

SELECT M.MANAGER_ID
FROM EMPLOYEE E
LEFT OUTER JOIN MANAGER M
ON E.MANAGER_ID=M.MANAGER_ID
connect by NOCYCLE m.manager_id=prior e.employee_id
GROUP BY m.manager_id;
于 2013-12-16T11:59:33.773 回答