我有下表。
ORDER
ORDERNUMBER
CUSTOMERNUMBER
EmployeeNumber
订购日期
客户
CUSTOMERNUMBER
名称
地址
EMPLOYEE
EmployeeNumber
名称
地址
的OrderDetail
ORDERNUMBER
数量
说明
价格
让我们说ORDERDETAIL表有10条记录
我想写一个查询,它将从ORDERDETAIL表中返回10条记录,以包括员工姓名,员工地址,客户名称,客户地址和订单日期。
我知道我可以编写一个查询并使用INNER JOIN从ORDER表中获取信息,但是如何创建剩余的查询以从CUSTOMER和EMPLOYEE表中获取信息。
SELECT *
FROM OrderDetail D
INNER JOIN Order O
ON D.OrderNumber = O.OrderNumber;
答案 0 :(得分:2)
只需添加更多联接......
SELECT *
FROM OrderDetail D
JOIN Order USING (OrderNumber)
JOIN Customer USING (CustomerNumber)
JOIN Employee USING (EmployeeNumber)
您可能希望重新排序JOIN以便首先获得最小的表,因为这可以为您提供一些性能提升(取决于您的服务器版本,最新的将为您优化连接并可能实际执行加入“可能是最好的”方式。)
此外,至少在MySQL方言中,JOIN
隐式扩展为INNER JOIN
,并且写作
A JOIN B USING (COL)
相当于写作
A JOIN B ON (A.COL = B.COL)
答案 1 :(得分:1)
SELECT *
FROM OrderDetail D
INNER JOIN Order O ON D.OrderNumber = O.OrderNumber
INNER JOIN Eployee E on O.EployeeNumber = E.EployeeNumber
INNER JOIN Customer C on O.CustomerNumber = C.CustomerNumber
答案 2 :(得分:0)
如果你有
之间的外键引用ORDER.EmployeeNumber and EMPLOYEE.EmployeeNumber
ORDER.CustomerNumber and CUSTOMER.CustomerNumber
然后尝试这个
SELECT
E.name AS employeeName,
E.Address AS employeeAddress,
C.name AS customerName,
C.Address AS customerAddress.
O.OrderDate
FROM OrderDetail D
INNER JOIN Order O ON D.OrderNumber = O.OrderNumber
INNER JOIN EMPLOYEE E ON E.EmployeeNumber = 0.EmployeeNumber
INNER JOIN CUSTOMER C ON C.CustomerNumber= 0.CustomerNumber
LIMIT 0,10