SQL - 指定字段可能涉及多个表

时间:2013-04-10 16:59:56

标签: sql

我是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 CustomerID更改为ContactName,则查询将正常运行。但是,我知道问题是CustomerID字段同时位于CustomersOrders表中。提前感谢您的帮助。

3 个答案:

答案 0 :(得分: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对聚合进行分组。您还需要确保将表名称作为列的前缀以防止出现歧义。

答案 1 :(得分:1)

您必须使用tablename或别名限定字段名称...建议使用别名。 另外,建议您切换到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

答案 2 :(得分:-1)

应该是:

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