网站制作学习网Database→正文:in 和not in的优化
字体:

in 和not in的优化

Database 2024/4/10 20:34:12  点击:不统计


在sql 查询中经常用到in 和not in 的where 查询操作,最近学习说用EXISTS代替 in 更快速。
 
举例说明,A表有字段a  B表有字段b,查询在 A表a字段中存在,但不在 B表 b字段中的内容。
用 not in 的sql 
select a from A where a not in (select b from B);
 
如果用NOT EXISTS替代 in
select a from A NOT EXISTS (select 1 from B where B.b=A.a);
 
这样查询速度快很多; 
 
上述例子中的not in 也可以更改为in ,同理 NOT EXISTS 变更为 EXISTS
 
当 in 或者not in 用固定值时 ,比如A表字段a 不等于1,2,3
sql 
 select a from A where a not in (1,2,3)
 
转换为
select a from A where a!=1 and a !=2 and a!=3
 
以后查询 尽量不要用 in 和not in 。

·上一篇:ms sql server 2008 创建用户 >>    ·下一篇:网站制作学习网
推荐文章
最新文章