在 MySQL 查询中,为什么使用 join 而不是 where?

2021-11-20 00:00:00 sql database mysql

好像把两个或多个表组合起来,我们可以使用join或where.一个比另一个有什么优势?

It seems like to combine two or more tables, we can either use join or where. What are the advantages of one over the other?

推荐答案

任何涉及多个表的查询都需要某种形式的关联来将表A"的结果链接到表B".这样做的传统 (ANSI-89) 方法是:

Any query involving more than one table requires some form of association to link the results from table "A" to table "B". The traditional (ANSI-89) means of doing this is to:

  1. 在FROM子句中用逗号分隔的列表列出涉及的表
  2. 在 WHERE 子句中写出表之间的关联

  1. List the tables involved in a comma separated list in the FROM clause
  2. Write the association between the tables in the WHERE clause

SELECT *
  FROM TABLE_A a,
       TABLE_B b
 WHERE a.id = b.id

这是使用 ANSI-92 JOIN 语法重写的查询:

Here's the query re-written using ANSI-92 JOIN syntax:

SELECT *
  FROM TABLE_A a
  JOIN TABLE_B b ON b.id = a.id

从性能的角度来看:

<小时>

在支持(Oracle 9i+、PostgreSQL 7.2+、MySQL 3.23+、SQL Server 2000+)的情况下,使用任何一种语法都没有性能优势.优化器将它们视为相同的查询.但是更复杂的查询可以从使用 ANSI-92 语法中受益:

From a Performance Perspective:


Where supported (Oracle 9i+, PostgreSQL 7.2+, MySQL 3.23+, SQL Server 2000+), there is no performance benefit to using either syntax over the other. The optimizer sees them as the same query. But more complex queries can benefit from using ANSI-92 syntax:

  • 能够控制JOIN顺序——扫描表的顺序
  • 能够在加入之前对表应用过滤条件

使用 ANSI-92 JOIN 语法而不是 ANSI-89 的原因有很多:

There are numerous reasons to use ANSI-92 JOIN syntax over ANSI-89:

  • 更具可读性,因为 JOIN 条件与 WHERE 子句分开
  • 不太可能错过 JOIN 条件
  • 对 INNER 以外的 JOIN 类型提供一致的语法支持,使查询易于在其他数据库上使用
  • WHERE 子句仅用于过滤所连接表的笛卡尔积

ANSI-92 JOIN 语法是模式,而不是反模式:

ANSI-92 JOIN syntax is pattern, not anti-pattern:

  • 查询的目的更明显;应用程序使用的列是明确的
  • 它遵循尽可能使用严​​格类型的模块化规则.显式几乎普遍更好.

由于不熟悉和/或舒适,我认为继续使用 ANSI-89 WHERE 子句而不是 ANSI-92 JOIN 语法没有任何好处.有些人可能会抱怨 ANSI-92 语法更冗长,但这正是它明确的原因.越明确,越容易理解和维护.

Short of familiarity and/or comfort, I don't see any benefit to continuing to use the ANSI-89 WHERE clause instead of the ANSI-92 JOIN syntax. Some might complain that ANSI-92 syntax is more verbose, but that's what makes it explicit. The more explicit, the easier it is to understand and maintain.

相关文章