为什么我没有收到错误?数据库如何理解嵌套子查询中的相关列?

Shi*_*kar 4 sql sql-server oracle plsql plsqldeveloper

这是场景:我有两个表部门和员工.当我从表中选择一个不存在于该表中的列时,它会按预期抛出错误.但是,当我使用子查询并再次从同一个表中选择相同的列时,它正在工作.我不明白它如何可以忽略我的错误.

create table department
( DEPT_ID                    NUMBER(2),
 DEPT_NAME                  VARCHAR2(6) );

 insert into department values(1,'ch');

 create table employee
 ( EMP_ID                     NUMBER(2),
 EMP_NAME                   VARCHAR2(6),
 EMP_DEPT_ID                NUMBER(2)
 );

 insert into employee values(0,'ch',1);

--getting  error for below (ORA-00904: "DEPT_ID": invalid identifier)
 select dept_id
from employee;

 -- not getting any error and can see the output for below sql statement. How it can consider invalid column for employee table dept_id in this query.
 select *
from   department
where dept_id in 
(
-- Incorrect column name
select dept_id
from employee
);
Run Code Online (Sandbox Code Playgroud)

我用2个RDBMS oracle和MSSQL试过这个.情况与两者相同.我没有和别人核对过

jar*_*rlh 11

由于您没有限定列,因此您的查询

select *
from   department
where dept_id in 
(
-- Incorrect column name
select dept_id
from employee
);
Run Code Online (Sandbox Code Playgroud)

将被"评估"为

select d.*
from   department d
where d.dept_id in 
(
select d.dept_id
from employee e
);
Run Code Online (Sandbox Code Playgroud)

子查询可以引用其外部查询的列.当涉及多个表时,始终限定所有列!

你可能想要的是什么

select d.*
from   department d
where d.dept_id in 
(
select e.EMP_DEPT_ID
from employee e
);
Run Code Online (Sandbox Code Playgroud)