用 join 代替子查询有意义吗?
例如我有一个这样的查询。
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
。两者都对吗?或者它们甚至是相同的?
For example I have a query like that.
select col1 from t1 where col2>0 and col1 in (select col1 from t2 where col2>0)
As far as I understand, I can replace it by the following query:
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
In some answers I see join
in other inner join
. Are both right? Or they are even identical?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
连接通常更快,但最好的决定方法是进行基准测试。
A join is usually faster, but the best way to decide is to benchmark.
这就是你想做的吗?
JOIN 绝对是正确的选择
Is this what you're trying to do?
A JOIN is definitely the way to go here
更好的是:
Even better:
实际上这已经足够了
至于哪个更快,唯一确定的方法就是测试。但我建议,除非性能是真正的用户体验问题,否则更重要的问题是长期可维护性,其中 SQL 的清晰度是首要因素。在我看来,子查询方法更清楚地表达了您正在实现的功能
actually this is sufficient
As to which is faster, the only way to be sure is to test. But I would suggest that unless performance is a real user-experience issue, the more important issue is long-term maintainability, for which the clarity of the SQL is a prime factor. And the sub-query approach, to my mind, expresses the function you are implementing more clearly
遇到这样的问题,您无论如何都应该进行连接
,并且“连接”和“内部连接”之间没有区别。 “inner”可以省略,因为它是默认的;仅需要指定“外部”及其类型。然而,如果你这样写,“join”也可以省略:
With such a Problem you should go for a join in any case
and there is no difference between "join" and "inner join". The "inner" can be omitted because its the default; only the "outer" with its type has to be specified. However, the "join" can be omitted too if you write it like this:
什么有意义取决于您的编码标准。
我会避免对子查询与连接进行基准测试,直到查询本身得到优化(删除无关的连接、同义的 where 子句、过多的列检索)并且分析表明需要优化特定查询。
即便如此,您的时间可能最好花在定义 RDBMS 在执行期间使用的良好索引上。
What makes sense depends on your coding standards.
I would avoid benchmarking sub-queries vs joins until the query itself has been optimized (removing extraneous joins, tautologous where clauses, excessive column retrieval) AND profiling demonstrates the need to optimize a particular query.
Even then, your time is probably better spent on defining good indexes for the RDBMS to use during execution.
像这样的东西怎么样:
选择 t1.col1
从 t1 加入 t2 在 t2.col1 = t1.col1
AND t1.col2 > 0
And how about something like this:
select t1.col1
from t1 join t2 On t2.col1 = t1.col1
AND t1.col2 > 0
在许多情况下,查询优化器会将子查询重写为联接。如果你的子查询是其中之一,重写它会浪费时间。但如何判断是否是这种情况,我不知道。如果您当前的查询有问题,EXPLAIN 命令可能会帮助您解决。
In many cases the query optimiser will rewrite your sub-queries as joins. If your sub-query is one of them, rewriting it will be a waste of time. How to tell if that is the case, though, I don't know. If your current query is a problem, the EXPLAIN command will probably help you out.