2013-03-03 84 views
0

我想這樣做選擇客戶誰特別放置順序一年

顯示誰已經下了訂單,1996年

所有客戶的客戶名稱,我使用的這個

select 
    Customers.ContactName 
from Customers 
where 
    Customers.CustomerID = (
    select Orders.CustomerID 
    from Orders 
    where year(Orders.OrderDate)=1996 
); 

但它給出了一個錯誤。

數據庫是羅斯文

+0

你得到了什麼錯誤? – DevelopmentIsMyPassion 2013-03-03 20:24:29

+0

錯誤可能是您從子查詢返回多行?使用'WHERE Customers.CustomID IN(select ....)'而不是'Customers.CustomerId =(select ...)' – 2013-03-03 20:24:53

+0

yes Michael這是錯誤 – 2013-03-03 20:31:18

回答

2

我想象你的子查詢返回多個結果試試這個(注意IN):

select 
    Customers.ContactName 
from Customers 
where 
    Customers.CustomerID IN (
    select Orders.CustomerID 
    from Orders 
    where year(Orders.OrderDate)=1996 
); 
+0

+1。 。 。你解釋這個問題並用最簡單的方法解決它。 – 2013-03-03 20:36:31

1

嘗試與參加這樣

SELECT 
    c.ContactName 
FROM Customers c 
INNER JOIN Orders o 
    ON o.CustomerID = c.CustomerId 
WHERE YEAR(o.OrderDate) = 1996 
1

嘗試:

SELECT DISTINCT c.contactName -- DISTINCT because some customers might have multiple orders 
FROM customers c 
JOIN orders o 
    ON o.customerId = c.customerId 
    AND year(o.orderDate) = 1996 

爲了將子查詢與標量進行比較,您需要確保子查詢只返回一個結果(例如, G。通過使用SELECT TOP 1 ...或SELECT COUNT(*)...)。或者,您可以使用EXISTS檢查子查詢是否有行,或者使用IN檢查包含。但是,JOIN往往是這種查詢的首選方法,因爲在某些情況下,數據庫似乎更好地優化它們。