在项目中,有一个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';
Logo

更多推荐