IN子句中不存在列,但SQL运行

前端之家收集整理的这篇文章主要介绍了IN子句中不存在列,但SQL运行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用IN子句的查询.这是一个简化版本:
SELECT *
  FROM table A
  JOIN table B
    ON A.ID = B.ID
 WHERE B.AnotherColumn IN (SELECT Column FROM tableC WHERE ID = 1)

tableC没有Column列,但查询执行得很好而没有错误消息.有人可以解释为什么吗

解决方法

如果外部查询中的表具有该名称的列,则此方法将起作用.这是因为外部查询中的列名可用于子查询,您可能故意在子查询SELECT列表中选择外部查询列.

例如:

CREATE TABLE #test_main (colA integer) 
CREATE TABLE #test_sub (colB integer)

-- Works,because colA is available to the sub-query from the outer query. However,-- it's probably not what you intended to do:
SELECT * FROM #test_main WHERE colA IN (SELECT colA FROM #test_sub)

-- Doesn't work,because colC is nowhere in either query
SELECT * FROM #test_main WHERE colA IN (SELECT colC FROM #test_sub)

正如Damien所观察到的,保护自己免受这种不太明显的“陷阱”的最安全的方法是养成在子查询中限定列名的习惯:

-- Doesn't work,because colA is not in table #test_sub,so at least you get
-- notified that what you were trying to do doesn't make sense.
SELECT * FROM #test_main WHERE colA IN (SELECT #test_sub.colA FROM #test_sub)

猜你在找的MsSQL相关文章