表之间的连接

时间:2020-06-15 14:02:23

标签: mysql

我想知道在两个表(或更多表)之间创建连接的最佳方法是什么。 我已经看到了两种不同的方法。

在下一个示例中,我有2个表。 表1 具有customerId(键)和customerName。 表2 具有customerId(密钥)和CustomerPhone

表1:


LANGUAGES = (
    ('fr', 'French'),
    ('en', 'English'),
)

表2:

 customerId | customerName|  
============+=============+
 1          |  Josh       |  
 2          |  Nadia      |   

哪个查询是最佳查询,为什么:

 customerId | customerPhone|  
============+==============+
 1          |  123         |  
 2          |  456         |   

Query2:

SELECT Table1.customerId, Table2.customerPhone  
FROM   Table1, Table2  
WHERE  Table1.customerId = Table2.customerId  

3 个答案:

答案 0 :(得分:2)

第二种选择更为普遍,被认为是正确的选择,但是他们俩都在做同样的事情

答案 1 :(得分:1)

第一个查询首先进行交叉联接,然后减少结果以适合cflause的位置。

第二个通过检查ON子句中的条件是否满足来匹配表。

两者都一样,但是首先是减慢

答案 2 :(得分:1)

第一个查询是使用旧语法(SQL-89)编写的:

SELECT Table1.customerId, Table2.customerPhone  
FROM   Table1, Table2  
WHERE  Table1.customerId = Table2.customerId  

第二个查询是用现代语法(SQL-92)编写的:

SELECT Table1.customerId, Table2.customerPhone  
FROM   Table1   
Inner Join  Table2 ON Table1.customerId = Table2.customerId   

它们是等效的。使用SQL-92。使用SQL-92!