2011-04-25 76 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子句中同时是真实的,但在加入也是可能的。