日期:2014-05-17  浏览次数:20961 次

IN 的执行效率太低了,怎么提高?
学写了一个SQL,都是用IN的,发现效率非常低。EXISTS不太会用。
有A、B两个表,A(pid,name),B(cid,pid)。
现在要做的就是对A表进行筛选,如果A表中PID不在B表中,那么就把A表中的这条数据删掉。
DELETE FROM A a WHERE a.pid in(select b.pid from A b where b.pid not in(select c.pid from B c))

哪位高手能不能帮我重写一下这个SQL,让其效率提高?谢谢
------解决方案--------------------
DELETE FROM A a WHERE not exists(select 1 from B b where a.pid = b.pid)
------解决方案--------------------
delete from a where not exists (select 1 from b where b.pid=a.pid);

------解决方案--------------------
1)DELETE FROM A a WHERE a.pid in(select b.pid from A b where b.pid not in(select c.pid from B c))

其中子查询的where里的条件不受外层查询的影响,这类查询一般情况下,CBO自动优化会转成exist语句,也就是效率和exist一样,但多了隐式转换了。
2)如果a,b 表都很大的话,用in和exists是感觉不出来区别的
3)不要用NOT EXISTS ,可否试着用外连接来实现该功能?
4)pid上是否建立了索引等



------解决方案--------------------
引用:
SQL code??



1

delete from a where not exists (select 1 from b where b.pid=a.pid);


看是否能快点