select f1
from table1
where f1 in (select f1)
--running OK.
select f1
from table1
where f1 in (select f1 from tablex)
-- even the column f1 does not exist in tablex, running OK.
delete from table1
where f1 in (select f1 from tablex)
--If you do this, you may have an accident (delete all records from table1)
--even the column f1 does not exist in tablex.
以上3条SQL语句在SQL Server 2008-2017中都可以正常运行。
因为f1
没有前缀tablex
和不在中,tablex
所以它绑定到f1
from table1
。当然table1.f1
是在(table1.f1)
。
这不是错误,而是绑定在SQL中的工作方式。请参见“子查询(SQL Server)”-“限定子查询中的列名称”:
(...)如果子查询的FROM子句中引用的表中不存在某列,则该列将由外部查询的FROM子句中引用的表隐式限定。(...)
这是一个很好的例子,为什么养成始终限定列的习惯很有用-至少在涉及多个表时(通过子查询,联接等)。尝试
... in (select tablex.f1 from tablex)
然后您将得到预期的错误。
您还可以使用表别名来缩短合格的列,如下所示:
... in (select x.f1 from tablex x)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句