为什么我没有收到错误消息?数据库如何理解嵌套子查询中的相关列?
why i'm not getting error? how does database understand relevant column in nested subquery?
场景如下:
我有两个 table 部门和员工。当我从 table 中选择一个 table 中不存在的列时,它会按预期抛出错误。但是,当我使用子查询并再次从相同的 table 选择相同的列时,它正在工作。我不明白它怎么能忽略我的错误。
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
);
我已经用 2 个 RDBMS oracle 和 MSSQL 试过了。两者的情况相同。我没有和其他人核实过
由于您没有限定列,您的查询
select *
from department
where dept_id in
(
-- Incorrect column name
select dept_id
from employee
);
将"evaluated"变为
select d.*
from department d
where d.dept_id in
(
select d.dept_id
from employee e
);
子查询可以引用其外部查询的列。当涉及多个 table 列时,始终限定所有列!
您可能想要的是
select d.*
from department d
where d.dept_id in
(
select e.EMP_DEPT_ID
from employee e
);
场景如下: 我有两个 table 部门和员工。当我从 table 中选择一个 table 中不存在的列时,它会按预期抛出错误。但是,当我使用子查询并再次从相同的 table 选择相同的列时,它正在工作。我不明白它怎么能忽略我的错误。
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
);
我已经用 2 个 RDBMS oracle 和 MSSQL 试过了。两者的情况相同。我没有和其他人核实过
由于您没有限定列,您的查询
select *
from department
where dept_id in
(
-- Incorrect column name
select dept_id
from employee
);
将"evaluated"变为
select d.*
from department d
where d.dept_id in
(
select d.dept_id
from employee e
);
子查询可以引用其外部查询的列。当涉及多个 table 列时,始终限定所有列!
您可能想要的是
select d.*
from department d
where d.dept_id in
(
select e.EMP_DEPT_ID
from employee e
);