2016-11-27 55 views
-4

我有3個表 - customer,productcustomerproduct(包含客戶和他們購買的產品的鏈接表)。
我想列出每個客戶與他購買的產品而不是如何列出非客戶購買的產品?

顧客

Tom 
Jim 
Harry 

產品

Shampoo 
Brush 
Shoe 
Box 

Customerproduct

Jim | box 
Jim | brush 
Tom | brush 
Harry | shampoo 

所以,我的查詢應顯示:

Jim | shampoo 
Jim | shoe 
Tom | shampoo 
Tom | shoe 
Tom | box 
... 

我需要使用查找,讓我的客戶和產品。製作單獨的表CustomersandProducts表並手動輸入它不是一個選項。 當然,必須有一種方法可以使用NOT EXISTS,NOT IN等獲得結果嗎?

+1

您是否嘗試過的東西沒有?這是一個家庭作業問題嗎? –

+0

我有。我沒有得到理想的結果。如果我不使用查找並使用查詢來查找不匹配的記錄,則可以解決此問題。但是這並不能解決我的問題。 –

+0

請給我們查詢。 –

回答

0

首先,您需要將產品加入客戶和產品以獲得客戶和產品的所有排列組合。然後在實際的客戶產品表中查找。

嘗試以下查詢:

select c.cname,p.pname 
customers c, 
product p 
where c.name,p.name not in (
select cp_i.cname,cp_i.pname 
from customerproduct cp_i) 

這個查詢將是非常敏感的資源(CPU/IO等),如果行數在任何表格的高。

另一種方法:

select c.cname,p.pname 
customers c, 
product p 
where not exists (
select 1 
from customerproduct cp_i 
where cp_i.cname=c.cname 
and cp_i.pname=p.pname) 
+0

非常感謝!將不得不修改這個嘗試我自己的數據庫,但至少它給了我一個開始! –

+0

我在我的訪問查詢中輸入了以下內容,但出現語法錯誤:SELECT Table1.Customer,Table2.Product FROM Table1,Table2 WHERE Table1.Customer,Table2.Product NOT IN (SELECT Table3.Customer,Table3.Product FROM表3); –

+0

在Table1.Customer,Table2.Product NOT IN..it應該是(Table1.Customer,Table2.Product)之前添加支架NOT IN ...也讓我知道確切的錯誤描述。 –

相關問題