您好我想从Northwind数据库中选择订购此类产品的客户的名称,例如巴西客户。我在这里做了巴西产品:
select [ProductName]
from [dbo].[Products] join [dbo].[Order Details] on [dbo].[Products].ProductID = [dbo].[Order Details].ProductID
join [dbo].[Orders] on [dbo].[Order Details].OrderID = [dbo].[Orders].OrderID
join [dbo].[Customers] on [dbo].[Orders].CustomerID = [dbo].[Customers].CustomerID
where [Country] = 'Brazil'
但是现在呢?我怎么能找到它们?我试着这样做:
select [CompanyName], [ProductName]
from [dbo].[Customers] join [dbo].[Orders] on [dbo].[Orders].CustomerID = [dbo].[Customers].CustomerID
join [dbo].[Order Details] on [dbo].[Order Details].OrderID = [dbo].[Orders].OrderID
join [dbo].[Products] on [dbo].[Products].ProductID = [dbo].[Order Details].ProductID
where [ProductName] in (
select [ProductName]
from [dbo].[Products] join [dbo].[Order Details] on [dbo].[Products].ProductID = [dbo].[Order Details].ProductID
join [dbo].[Orders] on [dbo].[Order Details].OrderID = [dbo].[Orders].OrderID
join [dbo].[Customers] on [dbo].[Orders].CustomerID = [dbo].[Customers].CustomerID
where [Country] = 'Brazil')
但这也行不通:/
答案 0 :(得分:0)
由于CompanyName位于原始查询的Customer表中,因此只需从那里选择它即可。
select
[CompanyName]
, [ProductName]
from
[dbo].[Products]
join
[dbo].[Order Details]
on
[dbo].[Products].ProductID = [dbo].[Order Details].ProductID
join
[dbo].[Orders]
on
[dbo].[Order Details].OrderID = [dbo].[Orders].OrderID
join
[dbo].[Customers]
on
[dbo].[Orders].CustomerID = [dbo].[Customers].CustomerID
where
[Country] = 'Brazil'
答案 1 :(得分:0)
如果我理解你的问题(措辞不清楚),你需要做的只是将[Customer]
添加到select
语句中,而不是运行嵌套查询。您的问题要求选择客户的名称,因此它是select [Customer]
,而不是[Company], [Product]
。
希望有所帮助。
答案 2 :(得分:0)
您理解架构错误。来自巴西的产品需要检查供应商
SELECT ProductID
FROM Products P
JOIN Suppliers S
ON P.SupplierID = S.SupplierID
WHERE S.Country = 'Brazil'
然后客户购买巴西产品
SELECT DISTINCT C.CustomerID
FROM Customer C
JOIN Orders O
ON C.CustomerID = O.CustomerID
JOIN OrderDetails OD
ON O.OrderID = OD.OrderID
WHERE OD.ProductID IN ( SELECT ProductID
FROM Products P
JOIN Suppliers S
ON P.SupplierID = S.SupplierID
WHERE S.Country = 'Brazil')