简体   繁体   English

内部连接条件或在哪里使用?

[英]inner join on condition or using where?

i have this query 我有这个查询

SELECT t1.col1
FROM table1 t1
INNER JOIN table2 t2 ON t2.col1 = t1.col1
WHERE t2.col IN (1, 2, 3)

and this query 和这个查询

SELECT t1.col1
FROM table1 t1
INNER JOIN table2 t2 ON t2.col1 = t1.col1 AND t2.col IN (1, 2, 3)

both game me the same execution plan and told me 都给我一个相同的执行计划,并告诉我

Using where;

does that mean that my 2nd query is converted to the first form from the optimizer and that i should follow the first form? 这是否意味着我的第二个查询已从优化器转换为第一种形式,并且我应该遵循第一种形式?

and is there a way to check the optimizer new query? 有没有办法检查优化器的新查询?

SQL is not a procedural language. SQL不是过程语言。 It is a descriptive language. 这是一种描述性语言。 A query describes the result set that you want to produce. 查询描述您要生成的结果集。

With an inner join, the two queries in your question are identical -- they produce the same result set under all circumstances. 使用内部联接,您的问题中的两个查询是相同的-它们在所有情况下都会产生相同的结果集。 Which to prefer is a stylistic preference. 首选哪个是风格偏好。 MySQL should treat the two the same way from an optimization perspective. 从优化的角度来看,MySQL应该以相同的方式对待两者。

One preference is that filters on a single table are more appropriate for WHERE and ON . 一种偏爱是单个表上的过滤器更适合WHEREON

With an outer join, the two queries are not the same, and you should use the one that expresses your intent. 对于外部联接,这两个查询是不相同的,您应该使用一个表达您的意图的查询。

The first one filters after joining the two tables; 连接两个表后的第一个过滤器; while the second one joins using the filtering of the values as a condition of joining the two tables. 而第二个表使用值过滤作为连接两个表的条​​件进行连接。 You may check this thread: 您可以检查此线程:

SQL join: where clause vs. on clause SQL连接:where子句与on子句

您可以检查执行两个查询需要花费多少,但是无论如何,您都可以用两种方式编写查询,无论是第一个查询还是第二个查询,优化器都会尝试优化查询。

I like this rule: 我喜欢这个规则:

  • ON ... says how the tables are related . ON ...说明表之间的关系
  • WHERE ... filters the results. WHERE ... 筛选结果。

This becomes important with LEFT JOIN because ON does not act as a filter. 这对于LEFT JOIN来说很重要,因为ON不能充当过滤器。

This shows you that the Optimizer treats them the same: 这表明您优化器对待它们的方式相同:

EXPLAIN EXTENDED SELECT ...
SHOW WARNINGS;

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

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