当前位置:首页 » 操作系统 » 数据库优化notin

数据库优化notin

发布时间: 2023-06-05 08:04:25

sql优化 - 避免使用 IN 和 NOT IN

1、效率低

2、容易出现问题,或查询结果有误 (不能更严重的缺点)

1、用 EXISTS 或 NOT EXISTS 代替

select * from test1
where EXISTS (select * from test2 where id2 = id1 )
select * FROM test1
where NOT EXISTS (select * from test2 where id2 = id1 )

2、用JOIN 代替

select id1 from test1
INNER JOIN test2 ON id2 = id1
select id1 from test1
LEFT JOIN test2 ON id2 = id1
where id2 IS NULL
妥妥的没有问题了!

PS:那我们死活都不能用 IN 和 NOT IN 了么?并没有,一位大神曾经说过,如果是确定且有限的集合时,可以使用。如 IN (0,1,2)。

❷ 求优化一句sql语句,not in速度太慢了

有俩种方法可以提高查询效率, 1、 用not exists 代替 not in , 这种发法没有改变查询数据的形式,所以可能效果不明显。 2、 利用索引查询, select tbl1.id from table1 tbl1 left join table2 tbl2 on tbl1.id = tbl2.id where tbl2.id = null; 这个是把table2表过滤,查询直接找索引。

热点内容
java返回this 发布:2025-10-20 08:28:16 浏览:645
制作脚本网站 发布:2025-10-20 08:17:34 浏览:936
python中的init方法 发布:2025-10-20 08:17:33 浏览:632
图案密码什么意思 发布:2025-10-20 08:16:56 浏览:821
怎么清理微信视频缓存 发布:2025-10-20 08:12:37 浏览:731
c语言编译器怎么看执行过程 发布:2025-10-20 08:00:32 浏览:1066
邮箱如何填写发信服务器 发布:2025-10-20 07:45:27 浏览:299
shell脚本入门案例 发布:2025-10-20 07:44:45 浏览:160
怎么上传照片浏览上传 发布:2025-10-20 07:44:03 浏览:851
python股票数据获取 发布:2025-10-20 07:39:44 浏览:763