在编写SQL语句时,假设要实现一张表有而另外一张表没有的数据时。 通常第一直觉的写法是:

select * from table1 where table1.id not in(select id from table2)

这样的写法尽管看起来非常直观。可是运行的效率会非常低下,在数据量非常大的时候效果尤其明显,我们推荐使用not exists或左连接来取代。

select a.* from table1 a left join table2 b on a.id=b.id where b.id is null

相同。这样的方法也适用于in