哪种方法更好地加入mysql表?

时间:2011-04-25 14:07:49

标签: mysql join

这两种从多个表中选择数据的方法有何不同。第一个不使用 JOIN 而第二个不使用。哪一个是首选方法?

方法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

3 个答案:

答案 0 :(得分:2)

对于你的简单案例,它们是等价的。即使方法#1中没有'JOIN'关键字,它仍然在进行连接。

但是,方法#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子句中不能同时为true,但在连接中是可能的。

答案 1 :(得分:0)

方法是apparently identical in performance,它只是新旧语法。

答案 2 :(得分:-1)

我认为没有多大区别。您可以使用EXPLAIN语句来检查MySQL是否做了不同的事情。对于这个微不足道的例子,我怀疑它是否重要。