(一个表)获取没有合并就没有的行

时间:2019-05-21 20:40:08

标签: sql postgresql

很抱歉,我只是不知道该如何简短地解释我要达到的目标。但这实际上很简单。

我有下表tf.Print

egr

我想获取未将groupid链接到另一个offid的行。结果将是:

+---------+------------+
|  offid  |  groupid   |
+---------+------------+
|       1 | 101        |
|       1 | 202        |
|       2 | 202        |
|       2 | 404        |
+---------+------------+

这行得通,但我想知道是否还有一种更优雅的方式?

+---------+------------+
|  offid  |  groupid   |
+---------+------------+
|       1 | 101        |
|       2 | 404        |
+---------+------------+

如果您想尝试:

select * from egr as egr1
where egr1.offid = 1
and egr1.groupid not in (select groupid from egr as egr2 where egr2.offid = 2 and egr1.groupid = egr2.groupid)
union
select * from egr as egr1
where egr1.offid = 2
and egr1.groupid not in (select groupid from egr as egr2 where egr2.offid = 1 and egr1.groupid = egr2.groupid)

谢谢

3 个答案:

答案 0 :(得分:1)

使用@mongo_client["orders"].indexes.create_one( { foo: 1, bar: 1 }, unique: true, name: "foobar" )

count()..over()

答案 1 :(得分:1)

这是您想要的吗?

select e.*
from egr e
where not exists (select 1
                  from egr e2
                  where e2.groupid = e.groupid and e2.offid <> e.offid 
                 );

或者如果您只想限制这两个优惠:

select e.*
from egr e
where e.offid in (1, 2) and
      not exists (select 1
                  from egr e2
                  where e2.groupid = e.groupid and 
                        e2.offid in (1, 2) and
                        e2.offid <> e.offid 
                 );

答案 2 :(得分:0)

这应该做

select groupid from egr group by groupid having count(distinct offid) =1