mysql ,表在数据量 很大的情况下,用 in 进行嵌套查询是效率很低的做法,通常出现 查询时间过长或直接数据库挂起,报错。
但 也有两种 解决办法:
原 查询:SELECT * from oms_contract where id
in (select contract_id from oms_contract_apply where customer_id='2c935b814959bcf5014959cef5ec0003');
解决方法一:SELECT * from `oms_contract` where id
in (select contract_id from (select contract_id from `oms_contract_apply` where customer_id='2c935b814959bcf5014959cef5ec0003' ) as arr);
解决方法二:SELECT * FROM `oms_contract` o INNER JOIN `oms_contract_apply` a ON o.id=a.contract_id where a.customer_id='2c935b814959bcf5014959cef5ec0003';
或者
SELECT * from oms_contract o,oms_contract_apply a where o.id=a.contract_id AND a.customer_id='2c935b814959bcf5014959cef5ec0003';
在执行时间 上,第二种更优于第一种。如果嵌套子查询 应尽量避免用in ,如果 是 常量 集合,用 in 也 并不影响查询效率。