SQL IN语句

时间:2012-01-23 16:50:31

标签: sql sql-server

  

可能重复:
  sql server 2008 management studio not checking the syntax of my query
  T-SQL Deletes all rows from a table when subquery is malformed

请参阅以下查询:

select * from tablea where reference in (
select reference from tableb)

tableb中不存在列reference,所以我希望看到一个错误,但是返回表a中的所有行。


为什么返回tablea中的所有行?

1 个答案:

答案 0 :(得分:5)

在子查询select reference from tableb内,您会看到来自上层查询的所有列,因此您的条件实际上就像“where 1 = 1”。

这是一个好建议的一个原因“如果你从多个表中选择,就给每个表别名”。例如,在您的情况下:

select a.* from tablea a where a.reference in (
select b.reference from tableb b)

这样你就可以得到预期的编译错误。