我需要创建一个SQL语句来获取以下信息: 多个表中的ISBN,Quantity,OrderTotal,FirstName,LastName,PhoneNumber和StreetAddress。
以下是我到目前为止提供的两个查询,它们为我提供了所需的信息:
CustomerInfo
SELECT c.CustomerID, c.FirstName, c.LastName, c.PhoneNumber, a.StreetAddress
FROM Customers AS c, Address AS a
WHERE c.CustomerID = a.CustomerID;
订单信息
SELECT o.CustomerID, o.OrderTotal, i.ISBN, i.Quantity
FROM Orders AS o, OrderItems as i
WHERE o.OrderID = i.OrderID;
CombinedQuery 这不起作用!!!
SELECT c.FirstName, c.LastName, c.PhoneNumber, c.StreetAddress, o.OrderTotal, o.ISBN, o.Quantity
FROM CustomerInfo as c, OrderInfo as o
WHERE c.CustomerID = o.CustomerID;
如何将前两个查询加入到一个查询中,该查询将提供第三个查询应提供的相同信息?
答案 0 :(得分:1)
CustomerId
中没有OrderInfo
字段。你需要所有三个表
SELECT c.FirstName, c.LastName, c.PhoneNumber, c.StreetAddress,
oi.OrderTotal, oi.ISBN, oi.Quantity
FROM (Customers as c INNER JOIN
Orders AS o
ON c.CustomerID = o.CustomerID
) INNER JOIN
OrderItems as oi
ON o.OrderID = oi.OrderID;
您还需要使用join
子句学习正确的on
语法。 where
子句中的隐式连接已过时,表达性较差,更容易出错。
答案 1 :(得分:0)
SELECT c.CustomerID, c.FirstName, c.LastName, c.PhoneNumber,
a.StreetAddress,
o.CustomerID, o.OrderTotal,
i.ISBN, i.Quantity
FROM Customers AS c, Address AS a, Orders AS o, OrderItems as i
WHERE o.OrderID = i.OrderID;
AND c.CustomerID = a.CustomerID
AND c.CustomerID = o.CustomerID;
尝试将其作为一个大查询而不是两个然后将它们组合起来。这将把所有四个表连接在一起。