使用left join代替not in

      发布在:数据库技术      评论:0 条评论

有这样的需求:查找在A表中存在,而在B表中不存在的数据,首先我们想到的应该是使用not in来查询。

构建的sql是这样的:

select * from a where a.username not in (select username from b)

看上去这个SQL并没有什么不妥,事实上,当两张表的数据量都不大情况下,确实也什么问题。

如果数据量大了,我们给两张表的username都加上索引,以为可以万事大吉了,可以实际发现username的索引并没有被使用。

那么如何解决这个问题呢?我们可以使用jeft join来曲线解决这个问题:

select a.* from a left join b on a.username=b.username where b.username is not null(包含的查询方式)

select a.* from a left join b on a.username=b.username where b.username is  null(不包含的查询方式)

这样一来,索引就可以被使用上了,效率大大提高。

来源:https://liyangweb.com/mysql/331.html


相关文章
热门推荐