mysql in查询效率真的低_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适合于外表小而内表大的情况。

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值