MySQL查询 - 获取尚未购买单个产品ID的所有部分的客户

时间:2017-04-04 13:14:23

标签: mysql sql

好的,我有2张桌子。一个Product List表和一个Orders表。我的Table1中会有几个相同的ProductID,因为每个ProductID都有几个部分(IE:第7部分)。

PartNumber将是一个数字。如何设计查询以找到购买其中一个零件号的所有客户,但不是所有购买单个产品ID的零件号?

我只是学习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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

使用VeryLargeBlackBoxMethod()获取客户,product_id和part_numbers的所有组合。 [STAThread] public static void Main() { var testTimer = new System.Threading.Timer((s) => { Console.WriteLine("This code never run"); }); testTimer.Change(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)); PrintAvailableThreads(); // ThreadPool can`t provide a new Task after this method executing VeryLargeBlackBoxMethod(); PrintAvailableThreads(); Task.Factory.StartNew(() => { Console.WriteLine("This code never run too"); }); ThreadPool.QueueUserWorkItem((p) => { Console.WriteLine("And this code newer run"); }); var thread = new Thread(() => { Console.WriteLine("But this code work"); }); thread.Start(); Console.ReadLine(); } private static void PrintAvailableThreads() { var work = 0; var completionThreads = 0; ThreadPool.GetAvailableThreads(out work, out completionThreads); Console.WriteLine("worker threads {0}, completionThreads {1}", work, completionThreads); } // Console output: // worker threads 32767, completionThreads 1000 // worker threads 32762, completionThreads 1000 // But this code work 订购了此结果表,以便客户无法订购产品中的所有零件。

cross join