2013-04-10 64 views
0

我是SQL的初學者,並且一直在玩弄它。有兩張桌子。一個叫做Customers,另一個叫Orders。我正在計算有多少訂單與客戶ID相關,但它一直在拋出一個錯誤。我有以下代碼:SQL - 指定的字段可能涉及多個表

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表中。預先感謝您的幫助。

回答

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 

此查詢使用明確JOIN語法是ANSI標準。這是最佳做法。你唯一缺少的是GROUP BY來聚合。您還需要確保將表名添加到列的前綴以避免歧義。

+0

Orders AS orders - legit syntax,but ... OP has it - 我仍然刪除無意義的別名。 – Andrew 2013-04-10 17:05:47

+0

感謝您的回覆。當我執行你的查詢時,我得到錯誤'FROM子句中的語法錯誤'。如果它的任何幫助,這是完美的查詢:SELECT ContactName,COUNT(orders.OrderID)AS TotalOrders FROM Customers AS cust,Orders AS orders WHERE cust.CustomerID = orders.CustomerID GROUP BY ContactName – InvertReality 2013-04-10 17:11:25

+0

@DavidMann什麼DBMS你正在用嗎? – Kermit 2013-04-10 17:16:25

-1

應該是:

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

缺少'GROUP BY';看起來像原來的。 – Kermit 2013-04-10 17:06:04

1

你必須用表名來限定字段名,或別名...使用別名建議。 此外,建議您切換到ANSI-92加入語法。

SELECT c.CustomerID, COUNT (o.OrderID) AS TotalOrders 
    FROM Customers c Join Orders o 
    On c.CustomerID = o.CustomerID 
    GROUP BY c.CustomerID 
+0

@Fresh ...正確,謝謝。 – 2013-04-10 17:04:30