0

因此,对于我的教授分配的一个有趣的小实验室,他希望我们使用不同的连接操作创建自己的查询。我很好奇的是 NATURAL JOIN 和 JOIN ON。

自然连接的教科书定义 - “返回匹配列中具有匹配值的所有行并消除重复列。” 所以,假设我有两个表,客户和订单。我列出了客户提交的所有 id = 1 的订单,如下所示:

Select Customers.Name
From Customers, Orders
Where Customers.ID = 1
AND Customers.ID = Orders.CID

我想知道这与 JOIN ON 有何不同,根据教科书“返回满足指定连接条件的行,通常包括两个表示列的相等比较”,即一个表的主键和一个表的外键其他。所以 JOIN ON 子句本质上与自然连接做同样的事情。它根据 ON 子句中指定的参数返回所有具有匹配值的行。

Select Customers.Name
From Customers JOIN Orders ON Customers.ID = Orders.CID

结果相同。后者只是编写自然连接的一种更简单的方法,还是我在这里遗漏了什么?

有点像 JavaScript 中的方式,我可以说:

var array = new Array(1, 2, 3);

或者我可以只使用更快更简单的文字,而无需构造函数:

var array = [1, 2, 3];

编辑:甚至没有意识到自然连接在 FROM 子句中使用了 JOIN 关键字,并省略了 WHERE 子句。这只是表明我对这种语言知之甚少。为了跟踪我自己的进度,我会保留错误。

4

1 回答 1

3

NATURAL JOIN is :

always an equi-join
always matches by equality of all of the same-named attributes

which in essence boils down to there being no way at all to specify the JOIN condition. So you can only specify T1 NATURAL JOIN T2 and that's it, SQL will derive the entire matching condition from just that.

JOIN ON is :

not always an equi-JOIN (you can also specify JOIN ON T1.A > T2.A)
not always involving all attributes that correspond by name (if both tables have an attribute named A, you can still leave out ON T1.A = T2.A).

Your ID/CID example is not suitable for using NATURAL JOIN directly. You would have to rename attributes to get the column/attribute matching you want by stating [something like] :

SELECT Customers.Name From Customers NATURAL JOIN (SELECT CID as ID FROM Orders)

(And as you stated in the question yourself, there is the thing about duplicate removal, which no other form of JOIN does by and of itself. It's an issue of scrutinous conformance to relational theory, which SQL as a whole doesn't exactly excel at, to put it mildly.)

于 2016-11-07T13:27:35.730 回答