通过join替换子查询是否有意义?

时间:2010-12-23 15:18:43

标签: mysql optimization select join subquery

例如我有这样的查询。

select col1 from t1 where col2>0 and col1 in (select col1 from t2 where col2>0)

据我了解,我可以通过以下查询替换它:

select t1.col1 from t1
join (select col1 from t2 where col2>0) as t2
on t1.col1=t2.col1
where t1.col2>0

ADDED

在某些答案中,我在其他join中看到inner join。都对吗?或者他们甚至相同?

8 个答案:

答案 0 :(得分:2)

加入通常更快,但最好的决定方法是进行基准测试。

答案 1 :(得分:1)

这是你想要做的吗?

select col1 from t1 
inner join t2 ON t2.col1 = t1.col1
where t1.col2>0 and t2.col2>0

JOIN绝对是这里的方式

答案 2 :(得分:1)

更好:

select t1.col1
    from t1
        inner join t2
            on t1.col1 = t2.col1
    where t1.col2>0
        and t2.col2>0

答案 3 :(得分:1)

实际上这已经足够了

select t1.col1 
from t1 join t2 On t2.col1 = t1.col1
Where t1.col2 > 0
   and t2.col2 > 0

至于哪个更快,唯一可以确定的方法是测试。但我建议除非性能是真正的用户体验问题,否则更重要的问题是长期可维护性,SQL的清晰度是其中的一个主要因素。在我看来,子查询方法表达了你正在更清楚地实现的功能

答案 4 :(得分:1)

遇到这样的问题,你应该在任何情况下加入

select t1.col1 
from t1 join t2 On t1.col1 = t2.col1
where t1.col2 > 0 and t2.col2 > 0

并且“join”和“inner join”之间没有区别。 “内部”可以省略,因为它是默认的;只需要指定其类型的“外部”。但是,如果你这样写,“join”也可以省略:

select t1.col1 
from t1, t2 
where t1.col2 > 0 and t2.col2 > 0 
  and t1.col1 = t2.col1

答案 5 :(得分:1)

有意义取决于您的编码标准。

我会避免对子查询与连接进行基准测试,直到查询本身已经过优化(删除无关连接,同义词子句,过多的列检索)和分析表明需要优化特定查询。

即使这样,你的时间也可能更好地用于定义RDBMS在执行期间使用的好索引。

答案 6 :(得分:0)

这样的事情怎么样:

select t1.col1 from t1 join t2 On t2.col1 = t1.col1
AND t1.col2 > 0

答案 7 :(得分:0)

在许多情况下,查询优化器会将子查询重写为连接。如果您的子查询是其中之一,重写它将是浪费时间。但是,我不知道如何判断是否是这种情况。如果您当前的查询有问题,EXPLAIN命令可能会帮助您。

相关问题