JOIN 比 WHERE 快吗? [英] Is a JOIN faster than a WHERE?

查看:32
本文介绍了JOIN 比 WHERE 快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个链接的表(一个有一个指向另一个的外键):

Suppose I have two tables that are linked (one has a foreign key to the other):

CREATE TABLE Document (
  Id INT PRIMARY KEY,
  Name VARCHAR 255
)

CREATE TABLE DocumentStats (
  Id INT PRIMARY KEY,
  DocumentId INT, -- this is a foreign key to table Document
  NbViews INT
)

我知道,这不是最聪明的做事方式,但这是我能想到的最好的例子.

I know, this is not the smartest way of doing things, but this is the best example I could come up with.

现在,我想获取浏览次数超过 500 次的所有文档.我想到的两个解决方案是:

Now, I want to get all documents that have more than 500 views. The two solutions that come to my mind are:

SELECT *
FROM Document, DocumentStats
WHERE DocumentStats.Id = Document.Id
  AND DocumentStats.NbViews > 500

或:

SELECT *
FROM Document
INNER JOIN DocumentStats ON Document.Id = DocumentStats.Id
WHERE DocumentStats.NbViews > 500

两个查询是否等效,还是有一种方法比另一种方法好得多?如果是,为什么?

Are both queries equivalent, or is there one way that is far better than the other? If so, why?

按照答案中的要求,这个问题是针对 SQL Server 的,但我很想知道它是否与其他数据库引擎(MySQL 等)不同.

as requested in the answers, this question was aimed at SQL Server, but I would be interested in knowing if it is different for other database engines (MySQL, etc...).

推荐答案

理论上,不,它不应该更快.查询优化器应该能够生成相同的执行计划.但是,一些数据库引擎可以为其中之一生成更好的执行计划(对于这样一个简单的查询,但对于足够复杂的查询,不太可能发生).您应该测试两者并查看(在您的数据库引擎上).

Theoretically, no, it shouldn't be any faster. The query optimizer should be able to generate an identical execution plan. However, some database engines can produce better execution plans for one of them (not likely to happen for such a simple query but for complex enough ones). You should test both and see (on your database engine).

这篇关于JOIN 比 WHERE 快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆