2011-04-25 127 views
4

這兩種從多個表中選擇數據的方法有什麼區別。第一個不使用JOIN而第二個。哪一個是首選的方法?哪種方法最好加入mysql表?

方法1:

SELECT t1.a, t1.b, t2.c, t2.d, t3.e, t3.f 
    FROM table1 t1, table2 t2, table3 t3 
WHERE t1.id = t2.id 
    AND t2.id = t3.id 
    AND t3.id = x 

方法2:

SELECT t1.a, t1.b, t2.c, t2.d, t3.e, t3.f 
FROM `table1` t1 
JOIN `table2` t2 ON t1.id = t2.id 
JOIN `table3` t3 ON t1.id = t3.id 
WHERE t1.id = x 
+0

[內連接相比交叉連接的性能]可能的重複(http://stackoverflow.com/questions/670980/performance-of-inner-join-compared-to-cross-join) – soulmerge 2011-04-25 14:17:58

回答

-1

我不覺得有什麼太大的差別。你可以使用EXPLAIN語句來檢查MySQL是否做了不同的事情。對於這個微不足道的例子,我懷疑它很重要。

2

對於你的簡單情況,它們是等價的。儘管'JOIN'關鍵字在方法1中不存在,但它仍在進行連接。

但是,方法#2提供了在JOIN條件中允許通過WHERE子句無法實現的額外條件的靈活性。比如當你對同一個表進行別名連接時。

select a.id, b.id, c.id 
from sometable A 
left join othertable as b on a.id=b.a_id and some_condition_in_othertable 
left join othertable as c on a.id=c.a_id and other_condition_in_othertable 

把兩個額外的條件,在whereclause會導致查詢返回任何東西,因爲這兩個條件不能在where子句中同時是真實的,但在加入也是可能的。