繁体   English   中英

MySQL中的子查询如何优化?

[英]How optimized are sub-queries in MySQL?

我的问题很长,但很简单。 我有以下几种查询:

select obj from table where condition1 and obj in (
select obj from table where condition2 and obj in (
select obj from table where condition3 and obj in (
...
)))

此查询需要很长时间。 恐怕MySQL以以下方式执行此查询(为简单起见,我们仅考虑一个子查询):

select obj from table1 where condition1 and obj in (select obj from table2 where condition2)

MySQL遍历表1的行。如果满足condition1 ,它将从子查询获得的集合中开始循环对象。 如果存在考虑的对象,则将其添加到对象的“最终”列表中。

我的问题是上面的示例在一个循环中有一个循环。 如果我有两个子查询,则在一个循环中有一个循环。 如果每个循环大约有10000个周期,那将是一场灾难。

我的解决方案是找到n套(每套对应一个select )。 然后,我独立地对每个集合进行循环(因此,循环中没有循环)。 这样的事情。

dictionary = []
for (elem in set1) {
   dictionary[elem] += 1
}
for (elem in set2) {
   dictionary[elem] += 1
}
for (elem in set3) {
   dictionary[elem] += 1
}

然后,再遍历dictionary所有元素,并仅选择在所有集合中找到的那些键:

finalSet = []
for (elem in dictionary) {
   if (dictionary[elem]==numberOfSets) {
      finalSet.add(elem)
   }
}

因此,我的问题是MySQL以我希望对其进行优化的方式进行了优化(上述方法)。 或者它在循环中产生循环。

添加

我只是认为可能可以通过重新编写查询来实现所需的优化。 代替:

select obj from table where condition1 and obj in (
select obj from table where condition2 and obj in (
select obj from table where condition3 and obj in (
...
)))

我应该写:

select obj from table where condition1
and obj in (select obj from table where condition2)
and obj in (select obj from table where condition3)
...

使用EXPLAIN查看MySQL如何执行查询,并查看JOIN重写查询。

SELECT
  t1.obj 
FROM 
  table1 AS t1
    JOIN table2 AS t2 ON (t1.obj = t2.obj AND condition2)
WHERE 
  t1.condition1

obj字段上的索引将加快处理速度,请检查EXPLAIN。

子查询不太适合优化。 如果可以使用其他方法,请避免对任何应用程序进行subs查询。 您最好使用以下查询:

从t1.obj = t2.obj上的表t1内部联接表t2和t2.condition ='condition'的表t1中选择t1.obj

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM