首页 > 解决方案 > 根据某些列选择尚未连接且唯一的记录

问题描述

我真的很难用一句话来清楚地表达我在标题中的问题。但这里是解释和示例数据:

https://www.db-fiddle.com/f/tfamoNxujZhfTzxPPzefLt/2

create table customer_promotions (
customer_id integer, 
promotion_id integer);

create table promotions (
  promotion_id integer,
  type text,
  product_type text,
  percentage integer);

  insert into customer_promotions values 
  (1,1), 
  (1,5), 
  (2,3),
  (2,4),
  (3,6),
  (4,2);
  insert into promotions values 
  (1,'fixed_value', 'food',5),
   (2,'fixed_value', 'food',10),
    (3,'percentage', 'food',10),
     (4,'percentage', 'clothes',10),
      (5,'fixed_value', 'electronics',20),
       (6,'percentage', 'electronics',10),
        (7,'fixed_value', 'toys',15);

我想查找特定客户的所有促销活动(比如说customer_id = 1),尚未使用(存在于表 customer_promotions 中)并且不共享相同typeproduct_type已在使用中。

所以对于客户 1 的结果应该是:promotion_id 3 4 6 7 我相信有一些使用左连接的简单解决方案,但我现在想到了黑洞。非常感谢您的帮助。

标签: sqlpostgresqlpostgresql-10

解决方案


您可以这样做:您的字段 type 和 product_type 使它们成为 varchar(100) 而不是文本。

   select * from promotions a 
   where not exists(select 1 from customer_promotions b 
   where a.promotion_id = b.promotion_id and b.customer_id = 1)
   and not exists
   (select 1 from promotions aa inner join 
   customer_promotions bb on aa.promotion_id = bb.promotion_id 
   where a.type = aa.type and a.product_type  = aa.product_type and bb.customer_id = 1)

输出:

promotion_id    type        product_type    percentage
3             percentage    food            10
4             percentage    clothes         10
6             percentage    electronics     10
7             fixed_value   toys            15

推荐阅读