SQL JOIN where to place the WHERE condition?

前端 未结 3 723
独厮守ぢ
独厮守ぢ 2020-12-08 04:25

I have two following examples.

1. Example (WHERE)

SELECT 1
  FROM table1 t1
  JOIN table2 t2 ON t1.id = t2.id
 WHERE t2.field = true         


        
相关标签:
3条回答
  • 2020-12-08 04:50

    I think the faster way is to put the filter in the where clause, because it will procees that filter in the where first , and then the join clause, so there will be no need of permutation of filters.

    0 讨论(0)
  • 2020-12-08 04:51

    JOIN conditions should normally be independent from filter conditions. You define rules of your join (the how) with ON. You filter what you want with WHERE. Performance wise, there's no general rule across all engines and designs, so your mileage will vary greatly.

    0 讨论(0)
  • 2020-12-08 05:07

    If a filter enters in a JOIN condition functionally (i.e. it is an actual join condition, not just a filter), it must appear in the ON clause of that join.

    Worth noting:

    • If you place it in the WHERE clause instead, the performances are the same if the join is INNER, otherwise it differs. As mentioned in the comments it does not really matter since anyway the outcome is different.

    • Placing the filter in the WHERE clause when it really is an OUTER JOIN condition implicitely cancels the OUTER nature of the condition ("join even when there are no records") as these filters imply there must be existing records in the first place. Example:

    ... table1 t LEFT JOIN table2 u ON ... AND t2.column = 5 is correct

    ... table1 t LEFT JOIN table2 u ON ... 
    WHERE t2.column = 5 
    

    is incorrect, as t2.column = 5 tells the engine that records from t2 are expected, which goes against the outer join. Exception to this would be an IS NULL filter, such as WHERE t2.column IS (NOT) NULL (which is in fact a convenient way to build conditional outer joins)

    • LEFT and RIGHT joins are implicitely OUTER joins.

    Hope it helped.

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