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

时间:2011-02-22 10:25:32

标签: sql sql-server-2008

我有一个使用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列,但查询执行得很好而没有错误消息。任何人都可以解释原因吗?

2 个答案:

答案 0 :(得分:14)

如果外部查询中的表具有该名称的列,则此方法有效。这是因为外部查询中的列名可用于子查询,您可能故意在子查询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)

答案 1 :(得分:3)

如果你想在将来避免这种情况(Matt Gibson已经解释过),那么总是习惯于使用别名来指定列。 E.g:

SELECT *
  FROM table A
  JOIN table B
    ON A.ID = B.ID
 WHERE B.AnotherColumn IN (SELECT C.Column FROM tableC C WHERE C.ID = 1)

这会给你一个很好的错误信息(注意我还在where子句中指定了别名 - 如果tableC中没有ID列,你还有其他问题)