有俩种方法可以提高查询效率, 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表过滤,查询直接找索引。
使用not exists 代替 not in
select tbl1.id from table1 tbl1 where not exists (select 1 from table2 tbl2 where tbl1.id = tbl2.id);
使用not exists 代替 not in
那就用 not exists
两种方案:
1、分别给两表的id加索引(效果显著)
2、不用子查询
select tbl1.id from table1 tbl1 left join tbl2 on tbl1.id=tbl2.id
where tbl2.id is null