0

我是 SQL 的初学者,并且一直在玩它。有两张桌子。一呼Customers一呼Orders。我正在计算有多少订单与客户 ID 相关,但它不断抛出错误。我有以下代码:

SELECT CustomerID, COUNT (orders.OrderID) AS TotalOrders
FROM Customers AS cust, Orders AS orders
WHERE cust.CustomerID = orders.CustomerID

它会引发一个错误,即该CustomerID字段可能出现在多个表中。

例如,如果我将其更改SELECT CustomerIDContactName,则查询将正常工作。但是,我知道问题在于该CustomerID字段同时在表CustomersOrders表中。提前感谢您的帮助。

4

3 回答 3

4

试试这个

SELECT cust.CustomerID, COUNT (orders.OrderID) AS TotalOrders
FROM Customers AS cust
JOIN Orders AS orders ON cust.CustomerID = orders.CustomerID
GROUP BY cust.CustomerID

此查询使用ANSI 标准的显式 JOIN语法。这是最佳实践。您唯一缺少的是GROUP BY对聚合进行分组。您还需要确保将表名添加到列的前缀以防止歧义。

于 2013-04-10T17:01:36.017 回答
1

您必须使用表名或别名来限定字段名称...建议使用别名。此外,建议您切换到 ANSI-92 Join 语法。

  SELECT c.CustomerID, COUNT (o.OrderID) AS TotalOrders
  FROM Customers c Join Orders o 
     On c.CustomerID = o.CustomerID
  GROUP BY c.CustomerID
于 2013-04-10T17:02:41.467 回答
-1

应该:

SELECT cust.CustomerID, COUNT (orders.OrderID) AS TotalOrders
FROM Customers AS cust, Orders AS orders
WHERE cust.CustomerID = orders.CustomerID
于 2013-04-10T17:02:10.393 回答