我有三种构造查询的方法:
第一个:
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/