【发布时间】:2018-11-17 18:49:37
【问题描述】:
我有一个包含 3 列 id 的表,clothes、shoes、customers 并将它们关联起来。
我有一个运行良好的查询:
select clothes, shoes from table where customers = 101(顾客101的所有衣服鞋子)。这会返回
clothes - shoes (SET A)
1 6
1 2
33 12
24 null
另一个运行良好的查询:
select clothes ,shoes from table
where customers in
(select customers from table where clothes = 1 and customers <> 101 )(101以外任何其他顾客的所有衣服鞋子,指定衣服)。这返回
shoes - clothes(SET B)
6 null
null 24
1 1
2 1
12 null
null 26
14 null
现在我想从 SET A 中获得所有不在 SET B 中的衣服和鞋子。
所以(示例)select from SET A where NOT IN SET B。这应该只返回衣服 33,对吧?
我尝试将其转换为有效的查询:
select clothes, shoes from table where customers = 101
and
(clothes,shoes) not in
(
select clothes,shoes from
table where customers in
(select customers from table where clothes = 1 and customers <> 101 )
) ;
我尝试了不同的语法,但上面看起来更符合逻辑。
问题是我从来不买衣服 33,只是一套空的。
我该如何解决这个问题?出了什么问题?
谢谢
编辑,这里是表格的内容
id shoes customers clothes
1 1 1 1
2 1 4 1
3 1 5 1
4 2 2 2
5 2 3 1
6 1 3 1
44 2 101 1
46 6 101 1
49 12 101 33
51 13 102
52 101 24
59 107 51
60 107 24
62 23 108 51
63 23 108 2
93 124 25
95 6 125
98 127 25
100 3 128
103 24 131
104 25 132
105 102 28
106 10 102
107 23 133
108 4 26
109 6 4
110 4 24
111 12 4
112 14 4
116 102 48
117 102 24
118 102 25
119 102 26
120 102 29
122 134 31
【问题讨论】:
-
你能包括你的整个样本数据集吗?
-
@Hambone 您具体需要什么?哪部分不清楚?
-
table的实际内容是什么。我可以猜到客户 101(第一个查询中的三条记录)有什么,但不能猜到表中还有什么。 -
@Hambone 再次检查问题
-
您的结果集 A 甚至不适合您假设的表格内容:44 2 101 1 46 6 101 1 49 12 101 33 52 101 24 它显然有 4 行,而不是 3,我建议在此处进行表备份并发布 sql 脚本
标签: postgresql subquery postgresql-10 in-subquery