mysql 关于子查询in条件问题记录

mysql 关于子查询in条件问题记录

####以下代码片段只为指明本次问题所用,不纠结好坏
1、外部条件改变内部查询方式
eg:select column1, column2, … from (

select c1, c2 from t1 where t.c1 in (
select c1 from t2 where t2.c3 = ? and t2.c4 in (?)
)

) t where t.c1 = ? and t.c2 = ? and t.c3 = ? and t.c4 = ?;

a、当外部条件较少时(最多存在3个: t.c1 = ? and t.c2 = ? and t.c3 = ? )
mysql 关于子查询in条件问题记录
发现sql 执行速度可以

b、当外部条件达到4个时(t.c1 = ? and t.c2 = ? and t.c3 = ? and t.c4 = ? )

mysql 关于子查询in条件问题记录
发现此时sql执行速度奇慢无比

百思不得其解,sql结构也没有改变只是原基础上加了一个筛选条件(and t.c4 = ?)啊!?为什么会慢这么多!两次查询也都用到了索引。。。

对比发现,两次不同出现在 select_type 中—— DEPENDENT SUBQUERY

DEPENDENT SUBQUERY :解释为子查询依赖外部查询
蒙了,不过问题确定就行;开始优化内部子查询语句,尤其是 in 语句
最后得到执行explain:
mysql 关于子查询in条件问题记录
核心在于derived 的产生,查询过程中将数据存于临时表中

2、大表中多字段的in语句
#不考虑分库分表分区
select t.c1, t.c2, … from table t where t.c1 in(?) and t.c2 in (?)
当表t 数据量比较大的时候,这个查询也会特别的慢;基于上面个的经验,于是想搞事情,抱着试一试的态度…

select c1, c2,… from
(select id, c1, c2, … from table where c1 in (?) ) t1,
(select id, c1, c2, … from table where c2 in (?) ) t2
where t1.id = t2.id
发现确实有点效果,前提是 t1, t2 两张表数据量都比较小