I want to to do following in northwind database:
Display the Product Names of all products that were placed by customers in CA but I'm confused how to relate a product with customer.
根据我的回忆,您需要将products
表加入orders
,orderDetails
和customers
表以获取客户订购的产品列表CA
:
select distinct p.ProductName
from customers c
inner join orders o
on c.customerId = o.customerId
inner join orderDetails od
on o.orderId = od.orderid
inner join products p
on od.productid = p.productid
where c.Region = 'CA'
或者您可以使用EXISTS
:
select p.ProductName
from products p
where exists (select od.productid
from customers c
inner join orders o
on c.customerId = o.customerId
inner join orderDetails od
on o.orderId = od.orderid
where c.Region = 'CA'
and p.productid = od.productid)
请参阅带有 两个查询示例的 SQL Fiddle 演示。
SELECT DISTINCT PRD.PRODUCTNAME
FROM CUSTOMERS AS CUST
INNER JOIN ORDERS AS ORD
ON CUST.CUSTOMERID=ORD.CUSTOMERID
INNER JOIN [ORDER DETAILS] AS ORDDETAILS
ON ORD.ORDERID=ORDDETAILS.ORDERID
INNER JOIN PRODUCTS AS PRD
ON ORDDETAILS.PRODUCTID=PRD.PRODUCTID
WHERE CUST.REGION='CA'
要按产品名称升序列出结果,请将其添加到末尾
ORDER BY PRD.PRODUCTNAME ASC
以下为我完成了这项工作
Select distinct Products.ProductName From Products
Where Products.ProductID in
(Select [Order Details].ProductID From [Order Details] Where [Order Details].OrderID in(select Orders.OrderID from Orders where Orders.CustomerID in(select Customers.CustomerID from Customers where Customers.Region='CA')))
order by Products.ProductName;
尝试这个:
Select o.pdt_name From orders o
Where o.cust_no in
(Select c.cust_no From customers c Where c.state = 'CA')
order by o.pdt_name