mysql - 什么查询最快?

标签 mysql optimization join subquery

我有三种构造查询的方法:

第一个:

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

第二个:

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

第三个:

select table1.obj from table1
inner join table2 on table2.obj = table1.obj and table2.condition='condition2'
inner join table3 on table3.obj = table2.obj and table3.condition='condition3'
...
where table1.condition='condition1'

我的问题是这些查询是否提供相同的结果以及这些查询是否同样最优。

我很确定前两个查询产生相同的输出,但第二个查询更快。我不确定第三个查询。

已添加

还有一个选择:

select table1.obj from table1
inner join table2 on table2.obj = table1.obj
inner join table3 on table3.obj = table2.obj
...
where
table1.condition='condition1' and 
table2.condition='condition2' and 
table3.condition='condition3'

最佳答案

虽然总有异常(exception),但选项 3 几乎肯定是最佳/首选。根据您的索引和数据分布,MySQL 查询执行计划器将处理从表中提取的顺序。

在其他情况下,子查询(选项 1 和 2)针对外部查询的每一行 执行——它们可能非常低效。因此,按照前面的陈述,嵌套子查询(选项 1)可能比使用一阶子查询(选项 2)或普通连接(选项 3)差指数级。

请注意,对于 INNER JOIN,如果 JOIN 中有额外条件,则性能功能无关紧要子句或 WHERE 子句中。因此,您的其他选项实际上等同于选项 3。

关于mysql - 什么查询最快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4470991/

相关文章:

mysql - 我需要优化以下sql查询

java - 我如何在 MySQL 数据库中保存图像 - 给出的代码

算法的运行时间优化

php - 如何调整 PHP 真实路径缓存?

sql - 如何将连接范围之外的数据捕获到 tempTBL 中

mysql - 将两个单独的联接合并到一个查询中

mysql - 我可以在 GROUP BY 和 ORDER BY 上强制使用 2 个单独的索引吗?

java - 数据库中的灵活搜索

MySQL 通过 SSH + Bash 错误

c# - 有没有更好的方法来调用 C# 中对象列表的比较?