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';
  • 6
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值