`

MySql中in查询效率低的替代方法

 
阅读更多

在项目中,有一个in查询效率很低,耗时大概10多秒,修改后为1秒左右,本来想造一组数据展现效果的,发现实际情况比较复杂,跟具体的关联数据类型、列是否有索引等相关,实际情况并不是某种查询就肯定比另一种查询效率高。在此不再费心思造数据,仅列出几种可能的查询方法,以备需要时尝试。

 

1. in查询实现

select * from product 

where id in (select rela_id from product_rela where id = '1');

 

2. 给in查询包一层temp

select * from product 

where id in (select rela_id from (select rela_id from product_rela where id = '1') as temp);

 

这种方法与普通的in查询相比,只是给in的子查询包装了一层select xxx from( ... )as temp,看似没做什么,但我在项目中通过此方法确实提高了查询效率,具体原理有待进一步考证。

 

3. 使用exists查询代替in查询

select * from product a 

where EXISTS (select rela_id from product_rela b where a.id=b.rela_id and b.id = '1'); 

 

4. 将in查询改为连接查询

select * from product a 

INNER JOIN product_rela b 

on a.id= b.rela_id and b.id='1';

 

 

mysql中 并不是exists一定比in效率快

一、关于exists和in的效率问题: 

分场景:

 

1.此场景适应A表数据量大于B表,且where后的字段加了索引。这种情况用in效率高的原因是利用了大表的索引。

  select * from ecs_goods A where A.cat_id in(select cat_id from ecs_category B);

  -------------------------------------------------------------------------------

2.此场景适应B表数据量大于A表,且where后的字段加了索引。这种情况用exists效率高的原因是利用了大表的索引。

  select * from ecs_goods a where EXISTS(select cat_id from

    ecs_category b where a.cat_id = b.cat_id);

 

总结:IN适合于外表大而内表小的情况;EXISTS适合于外表小而内表大的情况。

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics