我有一个包含 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
现在我想从 A 组中获取 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
最佳答案
PostgreSQL 中的 except
子句的工作方式与 Oracle 中的 minus
运算符的工作方式相同。我认为这会给你你想要的。
我认为理论上您的查询看起来是正确的,但我怀疑那些讨厌的空值正在影响您的结果。就像 null 不等于 5(它什么都不是,因此它既不等于也不不等于任何东西),null 也不“不”在任何东西中......
select clothes, shoes
from table1
where customers = 101
except
select clothes, shoes
from table1
where customers in (
select customers
from table1
where clothes = 1 and customers != 101
)
关于PostgreSQL : comparing two sets of results does not work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53354429/