sql - 根据某些列选择尚未连接且唯一的记录
问题描述
我真的很难用一句话来清楚地表达我在标题中的问题。但这里是解释和示例数据:
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 中)并且不共享相同type
且product_type
已在使用中。
所以对于客户 1 的结果应该是:promotion_id 3 4 6 7 我相信有一些使用左连接的简单解决方案,但我现在想到了黑洞。非常感谢您的帮助。
解决方案
您可以这样做:您的字段 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
推荐阅读
- regex - 正则表达式验证字符串的前后斜杠
- python - 有没有一种使用内部元素很少的多个数据框进行预测的方法?
- android - 如何解决这个 android 模拟器错误的大小调整?我正在使用 vscode 但模拟器显示如下
- java - 使用 Java 将 JSON 转换为 POJO 并赋值
- go - gorm 与 foreignKey 参考有很多关系
- docker - 在 Docker 容器下的 GStreamer 管道之间共享内存
- python - 维度不匹配的数量 - Tensorflow
- typescript - 如何调用从父类继承的异步函数?
- python - 获取 FileNotFoundError:[Errno 2] 没有这样的文件或目录:(PYTHON)
- magento - Magento 2 WYSIWYG 编辑器按钮不起作用