【问题标题】:Select distinct id with two types postgresql使用两种类型的 postgresql 选择不同的 id
【发布时间】:2015-09-22 18:52:33
【问题描述】:

我有可以有两种类型的 orderid,我需要选择仅存在一种的不同 orderid。

数据如下:

orderid 1 type 1
orderid 1 type 2
orderid 2 type 1
orderid 2 type 1 

我想选择只存在type 1的orderid。

我试过了:

select distinct orderid from orders where type=1 and type<>2

返回 orderid 1 和 2

【问题讨论】:

  • type=1 and type&lt;&gt;2 这肯定会优化为type=1,因为根据定义,如果它等于 1,它就不能同时等于 2。两个(不同的 orderid)记录都有 1 行 type=1 所以它应该返回两个?我的 10 秒看看它。
  • @DarrylMiles OP 只想要 orderid = 2,因为它没有类型 2 的记录

标签: sql postgresql distinct


【解决方案1】:

您可以使用except 来执行此操作。

select orderid from orders where type = 1 
except
select orderid from orders where type <> 1 

【讨论】:

    【解决方案2】:

    你可以使用group by:

    select orderid
    from orders
    group by orderid
    having min(type) = 1 and max(type) = 1;
    

    不需要distinctorderid 只返回一次。

    【讨论】:

      猜你喜欢
      • 2020-06-24
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      相关资源
      最近更新 更多