性能优化-子查询的优化

3、子查询的优化

子查询是我们在开发过程中经常使用的一种方式,在通常情况下,需要把子查询优化为join查询但在优化是需要注意关联键是否有一对多的关系,要注意重复数据。

查看我们所创建的t表

show create table t;

在这里插入图片描述
接下来我们创建一个t1表

create table t1(tid int);

并插入一条数据
在这里插入图片描述
我们要进行一个子查询,需求:查询t表中id在t1表中tid的所有数据;

select * from t where t.id in (select t1.tid from t1);

在这里插入图片描述
接下来我们用join的操作来进行操作

select id from t join t1 on t.id =t1.tid;

在这里插入图片描述
通过上面结果来看,查询的结果是一致的,我们就将子查询的方式优化为join操作。

接下来,我们在t1表中再插入一条数据

insert into t1 values (1);
select * from t1;

在这里插入图片描述
在这种情况下,如果我们使用子查询方式进行查询,返回的结果就是如下图所示:
在这里插入图片描述
如果使用join方式进行查找,如下图所示:
在这里插入图片描述
在这种情况下出现了一对多的关系,会出现数据的重复,我们为了方式数据重复,不得不使用distinct关键词进行去重操作

select distinct id from t join t1 on t.id =t1.tid;

在这里插入图片描述
注意:这个一对多的关系是我们开发过程中遇到的一个坑,出现数据重复,需要大家注意一下。

例子:查询sandra出演的所有影片:

explain select title,release_year,length 
 from film 
 where film_id in (
 select film_id from film_actor where actor_id in (
 select actor_id from actor where first_name='sandra'));
发布了1077 篇原创文章 · 获赞 888 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/103993444