【问题标题】:SQL Server using IN operator with subquery seems to be a BUG? [duplicate]使用带有子查询的 IN 运算符的 SQL Server 似乎是一个 BUG? [复制]
【发布时间】:2020-04-24 14:14:24
【问题描述】:
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 中都可以正常运行。

【问题讨论】:

    标签: sql sql-server sql-server-2017


    【解决方案1】:

    由于f1 没有以tablex 为前缀并且不在tablex 中,因此它从table1 绑定到f1。当然table1.f1(table1.f1)

    这不是错误,这就是绑定在 SQL 中的工作方式。见"Subqueries (SQL Server)" - "Qualifying column names in subqueries"

    (...) 如果子查询的 FROM 子句中引用的表中不存在列,则外部查询的 FROM 子句中引用的表隐式限定该列。 (...)

    这是一个很好的例子,说明为什么养成始终限定列的习惯会很有用——至少在涉及多个表时(通过子查询、连接等)。试试

    ... in (select tablex.f1 from tablex)
    

    你会得到你期望的错误。

    您还可以使用表别名来缩短限定列,如:

    ... in (select x.f1 from tablex x)
    

    【讨论】:

    • 非常感谢您的回答。是否有任何官方在线文档解释了这种现象。
    • @Ginger:查看编辑。
    • 你太棒了!谢谢ヽ(°◇°)ノ!
    • @Ginger 请将此标记为已接受的答案,以帮助未来的访问者。
    • @PratikBhavsar OK :-)
    猜你喜欢
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 2019-08-23
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多