create table tb2(xid int identity(1,1),name varchar(10)); insert into tb1(name)
select 'a'
union all select 'b'
union all select 'c'
insert into tb2(name) select 'x' select * from tb1 where id in(select id from tb2)
select * from tb1 where id in(select xid from tb2) drop table tb1
drop table tb2;
结果是:
id name remark
----------- ---------- --------------------------------------------------
1 a
2 b
3 c
id name remark
----------- ---------- --------------------------------------------------
1 a
从这段脚本执行后,就可以发现问题:
为何select * from tb1 where id in(select id from tb2)在执行的时候不对条件中的子查询语句做语法检查呢?而且默认的等价于1=1呢?
而且,select * from tb1 where id in(select id from tb2 where id=1)会按照select * from tb1 where id in(select xid from tb2 where xid=1)来执行,这说明子查询语句的语法没有被检查,但是过滤却起到了作用,这的确是很奇怪的事情。
如果我在敲sql语句的时候误把 select * from tb1 where id in(select xid from tb2)中的select xid敲成select id,那么取出的数据就会有问题(全取出),但是却得不到提示,因为语法检查跳过了。所以,这个在写sql语句的时候,就是一个潜在的泥坑。
据说在oracle中也存在类似的问题,没有试。
大家在写sql脚本时,还是要谨慎啊,因为今天早上我的sql就出现了这样的问题,谨记教训啊。