2017-04-04 70 views
1

好吧,我有2個表格。一張表格爲Product List,另一張表格爲Orders。在我的Table1中會有幾個相同的ProductID,因爲每個ProductID都有幾個部分(IE:7的第1部分)。MySQL查詢 - 獲得沒有購買單個產品ID的所有部分的客戶ID

PartNumber將是一個數字。如何設計我的查詢以找到所有已購買部件編號的客戶,而不是單個產品編號的所有部件編號?

我只是學習MySQL的基礎知識,所以任何幫助將不勝感激!

表1 - 產品列表

UniqueIDKey 
Product ID 
PartNumber 

表2 - 訂單

UniqueIDKey 
Product ID Ordered 
PartNumber Ordered 
Customer ID 

所以訂單可能是這樣的:

UniqueIDKey: 77 
Product ID Ordered: 1001 
PartNumber Ordered: 3 
Customer ID: 2000001 

而且,我的Table1 - Product List的幾行可能看起來像這個:

UniqueIDKey  Product ID  PartNumber 
77    1001   1 
78    1001   2 
79    1001   3 
+0

什麼是你的策略是什麼?我的意思是你到目前爲止所嘗試過的?請隨時分享。 – 1000111

回答

1
  • 你需要知道的部分,每個部分產品在總數之前 以瞭解哪些客戶購買了產品的某些部分,但不是全部 。
  • 由表別名B包圍的查詢提供 每個產品部分的計數。
  • 由表別名A包圍的查詢提供了每個 <customer,product>對購買部件的總數量。
  • 現在剩下的是匹配購買的零件總數是否小於產品零件總數的 。

在這種方法中查詢看起來象下面這樣:


SELECT 
A.customer_id, 
A.product_id, 
A.total_parts_of_product_customer_purchased AS total_purchased, 
B.total_parts, 
B.total_parts - A.total_parts_of_product_customer_purchased AS didnot_purchase 
FROM (
    SELECT 
    customer_id, 
    product_id, 
    count(part_number) AS total_parts_of_product_customer_purchased 
    FROM Orders AS ordr 
    GROUP BY 
     customer_id, product_id 
) AS A 
INNER JOIN (
    SELECT 
    product_id, 
    count(part_number) AS total_parts 
    FROM product_list AS pl 
    GROUP BY product_id 
) AS B 
ON A.product_id = B.product_id 
WHERE A.total_parts_of_product_customer_purchased < B.total_parts 
ORDER BY A.customer_id; 
+0

目前,每個產品ID的零件數量變化相當隨機。 ProductID通常具有1到35個部分。任何建議與此? – Linuxmint

+1

可變數量的產品部件有什麼問題?你有什麼問題嗎?不同的產品可能有不同數量的零件。這似乎是合法的。 – 1000111

0

使用cross join得到的客戶,PRODUCT_ID的和part_numbers所有組合。 left join對此結果訂單表以獲得尚未訂購產品中所有零件的客戶。

select c.customer_id,p.product_id 
from (select product_id,part_number from product_list) p 
cross join (select distinct customer_id from orders) c 
left join orders o on p.product_id=o.product_id and p.part_number=o.part_number and c.customer_id=o.customer_id 
group by c.customer_id,p.product_id 
having count(o.part_number) < count(p.part_number) 
+0

也許我做錯了什麼,但是這個查詢對我來說運行得非常慢。任何提示加快它? – Linuxmint