私はノースウィンドデータベースで次のことをしたい:
顧客が CA に配置したすべての製品の製品名を表示しますが、製品を顧客 と関連付ける方法がわかりません。
私の回想に基づいて、テーブルをに結合し、テーブルを結合して、顧客が注文した製品のリストを取得する必要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フィドルを参照してください。
これを試して:
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
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;