【问题标题】:(One table) get rows not in without union(一个表)获取没有联合的行
【发布时间】:2019-05-21 20:40:07
【问题描述】:

对不起标题我只是不知道如何简要解释我想要实现的目标。但其实很简单。

我有下表egr

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

我想获取 groupid 未链接到其他 offid 的行。结果是:

+---------+------------+
|  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)

如果您想尝试:

create table egr (offid int, groupid int);
insert into egr values (1, 101), (1, 202), (2, 202), (2, 404);

谢谢

【问题讨论】:

    标签: sql postgresql


    【解决方案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 
                     );
    

    【讨论】:

    • 插入 offid 1 缺失的 groupid 的插入语句是什么(但 offid 2 有哪个)?基本上是添加值 (1, 404)
    • @StephaneB。 . . .这是一个不同的问题,应该作为问题提出。
    【解决方案2】:

    使用count()..over()

    select groupid,offid
    from (select groupid,offid,count(*) over(partition by groupid) as cnt
          from tbl
         ) t
    where cnt = 1
    

    【讨论】:

      【解决方案3】:

      应该这样做

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

      【讨论】:

        猜你喜欢
        • 2015-01-18
        • 1970-01-01
        • 2016-05-21
        • 2011-12-31
        • 1970-01-01
        • 2017-10-17
        • 1970-01-01
        • 2010-09-22
        • 1970-01-01
        相关资源
        最近更新 更多