0

为什么这会正确返回Order ID订单的、下Customer ID订单的人和Last Name负责交易的员工的

SELECT "OrderID", "CustomerID", "LastName"
FROM orders O 
NATURAL INNER JOIN customers JOIN employees ON O."EmployeeID" = employees."EmployeeID";

尽管

SELECT "OrderID", "CustomerID", "LastName"
FROM orders O 
NATURAL INNER JOIN customers NATURAL INNER JOIN employees;

返回 0 行?

我确信他们有共同的专栏。

Table orders OrderId EmployeeID CustomerID ...

Table employees EmployeeID ...

Table customers CustomerID ...

4

1 回答 1

1

如果没有看到完整的、未经编辑的架构,很难确定,但我想说常见的列比您预期的要多。

例如@ClockworkMuse 建议:

CREATE TABLE orders (
    OrderId integer primary key,
    EmployeeID integer not null,
    CustomerID integer not null,
    created_at timestamp not null default current_timestamp,
    ...
);

CREATE TABLE employees (
    EmployeeID integer primary key,
    created_at timestamp not null default current_timestamp,
    ...
);

那么orders NATURAL JOIN employees将等价于orders INNER JOIN employees USING (EmployeeID, created_at)。这肯定不是你想要的。

您应该使用INNER JOIN ... USING (colname)INNER JOIN ... ON (condition)

NATURAL JOIN是一个经过深思熟虑的功能,除了快速和肮脏的临时查询(即使这样)之外,应该真正避免使用。即使它现在可以工作,如果您稍后将不相关的列添加到表中,它可能会改变现有查询的含义。那是......好吧,避免自然连接。

于 2014-10-06T12:52:28.523 回答