2012-01-23 110 views
2

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

请参阅下面的查询:

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

reference不TableB中存在,所以我希望看到一个错误,如何反而会返回表a中的所有行。


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

+5

Sql Server,Oracle,Sybase ASE,MySQL? –

+0

sql服务器。谢谢。 – w0051977

+0

不应该有'NOT IN'返回的行。 [你确定你没有使用'IN'?](http://stackoverflow.com/q/4594733/73226) –

回答

5

里面的子查询select reference from tableb你可以看到来自上层查询的所有列,所以你的条件实际上就像“where 1 = 1”一样工作。

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

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

这样你会得到预期的编译错误。

+0

是的,将查询更改为'select * from tablea where reference in(select tableb.reference from tableb)' –

+0

第二个查询说:从tableb中选择引用。但是,tableb中不存在引用。当然应该有一个错误?我明显错过了一些东西。谢谢。 – w0051977

+0

Olivier,您的评论按照您的描述进行。但是,为什么这不会产生语法错误,如“从tableb选择tableb.reference”(本身就是这样)。只要添加外部查询,内部查询就可以工作。 – w0051977