简体   繁体   English

SQL JOIN在何处放置WHERE条件?

[英]SQL JOIN where to place the WHERE condition?

I have two following examples. 我有两个以下的例子。

1. Example (WHERE) 1.示例(WHERE)

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

2. Example (JOIN AND) 2.示例(加入AND)

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

What is the faster way in terms of performance? 在性能方面,更快的方法是什么? What do you prefer? 你喜欢哪个?

If a filter enters in a JOIN condition functionally (ie it is an actual join condition, not just a filter), it must appear in the ON clause of that join. 如果过滤器在功能上进入JOIN条件(即它是一个实际的连接条件,而不仅仅是一个过滤器),它必须出现在该连接的ON子句中。

Worth noting: 值得注意:

  • If you place it in the WHERE clause instead, the performances are the same if the join is INNER , otherwise it differs. 如果将它放在WHERE子句中,如果连接是INNER ,则性能相同,否则它们不同。 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. WHERE子句确实是一个OUTER JOIN条件时,将过滤器放在WHERE子句中会隐含地取消条件的OUTER性质(即使没有记录时也加入),因为这些过滤器意味着必须首先存在现有记录。 Example: 例:

... table1 t LEFT JOIN table2 u ON ... AND t2.column = 5 is correct ... table1 t LEFT JOIN table2 u ON ... AND t2.column = 5是正确的

... 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. 是不正确的,因为t2.column = 5告诉引擎来自t2的记录是预期的,这与外部t2.column = 5 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) 对此的例外是IS NULL过滤器,例如WHERE t2.column IS (NOT) NULL (实际上是构建条件外连接的便捷方式)

  • LEFT and RIGHT joins are implicitely OUTER joins. LEFTRIGHT联接是隐含的OUTER连接。

Hope it helped. 希望它有所帮助。

JOIN conditions should normally be independent from filter conditions. JOIN条件通常应独立于过滤条件。 You define rules of your join (the how ) with ON . 您可以使用ON定义连接的规则( 方法 )。 You filter what you want with WHERE . 您可以使用WHERE过滤所需的内容 Performance wise, there's no general rule across all engines and designs, so your mileage will vary greatly. 性能方面,所有引擎和设计都没有一般规则,因此您的里程会有很大差异。

我认为更快的方法是将过滤器放在where子句中,因为它将首先进行过滤,然后是join子句,因此不需要对过滤器进行排列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM