問題描述
好像把兩個或多個表組合起來,我們可以使用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:
- 在FROM子句中用逗號分隔的列表列出涉及的表
在 WHERE 子句中寫出表之間的關聯
- List the tables involved in a comma separated list in the FROM clause
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.
這篇關于在 MySQL 查詢中,為什么使用 join 而不是 where?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!