mysql 相反结果集查询


今天闲来无事,开始整理数据库记录。想查询一张表中没有被另一张表引用的记录,然后删除之。上网查询的方法为:使用not exists或not in.

参考文章:http://wenku.baidu.com/view/fe5f5e0d76c66137ee0619ab.html

     http://hnwsha.blog.sohu.com/177433557.html

文章都总结说,无论大表小表,not exists都比not in 效率高.

但是我的测试结果如下:

A为大表,B为小表。差距为A表记录172683,B表记录84.

select count(*) from A;

0.031 sec / 0.000 sec

select count(*) from B;

0.000 sec / 0.000 sec

select * from B where not exists (select b from A
where a = 2 and b = B.b);

4.485 sec / 0.000 sec

select * from B where b not in (select b from A
where a = 2);

4.281 sec / 0.000 sec

结果分析:如果主查询为小表,且与子查询中的大表记录差距很大时,反而是not in 效率更高。但是要注意子查询中没有NULL值,否则没有返回集。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM