Is a JOIN faster than a WHERE?

前端 未结 10 1038
渐次进展
渐次进展 2020-11-29 05:44

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 TAB         


        
相关标签:
10条回答
  • 2020-11-29 06:05

    If you're talking specifically about SQL Server, then you should definitely be using the INNER JOIN syntax. Apart from being (personal opinion alert!) easier to read and more clear in intent, there is, as of SQL Server 2005, no equivalent syntax for outer joins. The *= and =* syntax is not supported by default in 2005 -- you need to enable a compatibility mode to support it. It will eventually be removed, possibly as soon as the next release (or possibly not!)

    This means:

    • If you need to change a query from inner join to outer join, you need to either rewrite it (argh) or enable compat mode (yuk)
    • Without compat mode, you can't be consistent with how you implement different types of joins (inner vs outer), making for a maintenance nightmare (and, where the two are combined in the one query, some behaviour that's non-intuitive).

    Note also that contrary to popular belief, the two are not equivalent. Some things are much more awkward, and some are simply not possible. Kalen Delaney's Inside SQL Server 2000 covers some examples; not sure if the newer editions do, because that join syntax is deprecated anyway.

    0 讨论(0)
  • 2020-11-29 06:07

    When you use Sqlite: The where-syntax is slightly faster because Sqlite first translates the join-syntax into the where-syntax before executing the query.

    0 讨论(0)
  • 2020-11-29 06:08

    I guess that it doesn't make a difference too. To be sure you can check if the explain plan of those two queries is identical. In order to look at the explain plan in MySQL you have to put the "explain" keyword before the statement, eg:

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

    I'm sure there exists an equivalent in MSSQL too.

    By the way: This looks like this is a 1:1 relationship so I'd just include the nbviews attribute directly in the Document table, therefore you can save a join.

    0 讨论(0)
  • 2020-11-29 06:14

    In MSSQL, both queries are compiled to the same execution plan, so there's no difference. It's more about readability - I think the JOIN is easier to read, so I use that.

    0 讨论(0)
  • 2020-11-29 06:20

    It is a "standard" to use the INNER JOIN syntax, although practically equivalent. The main reason it should be used is for clarity and mobility purposes as it is consistent with OUTER JOIN syntax.

    0 讨论(0)
  • 2020-11-29 06:21

    In MySQL at least, they will both be optimized to the same query.

    0 讨论(0)
提交回复
热议问题