使用自然联接时标识符无效

时间:2019-03-05 11:51:11

标签: sql oracle

我得到

  

ORA-00904:“ E”。“ MANAGER_ID”:无效的标识符   00904. 00000-“%s:无效的标识符”   *原因:
  *行动:   错误,错误:323,列:77

使用以下代码。在这段代码中,位置323列77指向位置5列6

    select concat (concat(concat('Id: ',e.employee_id),
    concat ('',e.first_name)),concat('. ',e.last_name)) as "Employee info", 
    job_title, salary, department_name, 
    (select first_name from employees 
    where e.manager_id=employee_id) as "Manager name"
    from employees e 
    natural join jobs natural join departments;

如果我执行查询“ isolated”,则为:

select e.first_name as "Worker name", nvl((select first_name from employees where e.manager_id=employee_id),'Sin manager') as "Manager name"
from employees e
order by e.employee_id;

我不知道这是否重要,但是该数据库是oracle内置的hr数据库

编辑:除答案外,我得出的另一种可能性是以下

select concat (concat(concat('Id: ',e.employee_id),
concat (' ',e.first_name)),
concat('. ',e.last_name)) as "Employee info", 
job_title, e.salary, department_name, m.first_name, m.employee_id
from employees e join jobs j
on (e.job_id = j.job_id)
join departments d
on (e.department_id = d.department_id)
join employees m
on (e.manager_id=m.employee_id)
order by e.employee_id;

唯一的问题是不会显示未分配经理的员工。

1 个答案:

答案 0 :(得分:1)

请勿使用自然联接!我将其描述为“令人讨厌的”,因为它使用的列仅具有相同的 names ,而不是正确声明的外键关系。关系数据库实际上应该对声明的关系进行“自然”连接,而不是对字符串匹配进行

这也使查询更难以解密和维护,因为联接键在查询中不是显式的。添加列可能会破坏现有查询,并且很难调试。

您还可以简化串联字符串的逻辑。

我认为您想要的查询看起来像这样:

select ('Id: ' || e.employee_id  || e.first_name || '.', e.last_name) as Employee_info, 
       j.job_title, e.salary, d.department_name, 
       (select em.
        from employees em
        where e.manager_id = em.employee_id
      ) as Manager_name
from employees e join
     jobs j
     on e.job_id = j.job_id join
     departments d
     on e.department_id = d.department_id;