我是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
字段同时位于Customers
和Orders
表中。提前感谢您的帮助。
答案 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