建表:
drop table t_test1;
drop table t_test2;
create table t_test1(
id number(10)
);
create table t_test2(
id number(10),
name varchar2(32),
status number(10)
);
insert into t_test2 (ID, NAME, STATUS)
values (1, 'a', 1);
insert into t_test2 (ID, NAME, STATUS)
values (1, 'b', 0);
insert into t_test2 (ID, NAME, STATUS)
values (2, 'a', 0);
insert into t_test1 (ID)
values (1);
insert into t_test1 (ID)
values (2);
t_test1
t_test2
待改造的语句: 假设t2是大表,这样查,数据量很大
select t1.* from t_test1 t1
left join t_test2 t2 on t1.id=t2.id
where 1=1 and t2.name='a' and t2.status=0;
查询结果:1条记录
改造:
select * from t_test1 t1 where
exists ( select 1 from t_test2 t2 where t1.id=t2.id and t2.name='a' )
and exists ( select 1 from t_test2 t2 where t1.id=t2.id and t2.status=0);
查询结果:多出了一条记录
分析:为什么会多出一条???
(1)select * from t_test1 t1 查出来是2条记录: id= 1,2
(2)exists ( select 1 from t_test2 t2 where t1.id=t2.id and t2.name='a' )
这一句过滤出 id相同,并且 name等于 a的记录, 查出的结果: id=1,2 因此 数据还是两条 id=1,2
(3)and exists ( select 1 from t_test2 t2 where t1.id=t2.id and t2.status=0);
再次检查是否存在,status等于0的记录,查出来的id还是 1,2,因此,满足条件,数据还是 两条,id=1,2
最后改成:
select * from t_test1 t1 where
exists ( select 1 from t_test2 t2
where t1.id=t2.id and t2.name='a' and t2.status=0);
分析:
(1)select * from t_test1 t1 查出来是2条记录: id= 1,2
(2)exists ( select 1 from t_test2 t2
where t1.id=t2.id and t2.name='a' and t2.status=0) 这一句查出来的记录只有一条 id=2,才满足条件。
所以最后的记录只有1条 ,id=1
总结:
所以以后改造成exists的时候,条件要放在一起,不能分开