【问题标题】:oracle - getting 1 or 0 records based on the number of occurrences of a non-unique fieldoracle - 根据非唯一字段的出现次数获取 1 或 0 条记录
【发布时间】:2011-09-21 16:12:44
【问题描述】:

我有一个表 MYTABLE

N_REC | MYFIELD |
1     | foo     |
2     | foo     |
3     | bar     |

其中 N_REC 是主键,MYFIELD 是非唯一字段。 我需要在 MYFIELD 上查询此表并提取关联的 N_REC,但前提是仅出现一次 MYFIELD;否则我不需要返回任何记录。 因此,如果我使用 MYFIELD='bar' 我会得到 3,如果我使用 MYFIELD='foo' 我不会得到任何记录。

我使用以下查询

select * from 
   ( 
   select 
     n_rec, 
     ( select count(*) from mytable where mycolumn=my.mycolumn ) as counter 
   from mytable my where mycolumn=? 
   ) 
where counter=1

虽然它给了我想要的结果,但我觉得我正在运行相同的查询两次。 有没有更好的方法来实现我正在做的事情?

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    我认为这应该做你想做的事:

    SELECT
        my_field,
        MAX(n_rec)
    FROM
        My_Table
    GROUP BY
        my_field
    HAVING
        COUNT(*) = 1
    

    【讨论】:

    • n_rec 是主键,所以 group by 应该在 MYFIELD 上完成。从 myfield=? 的 mytable 中选择 myfield, max(n_rec)按具有 count(*) = 1 的 myfield 分组
    【解决方案2】:

    您也可以尝试 count(*) 的分析或窗口版本,并将计划与其他选项进行比较:

    select n_rec, my_field
    from (select n_rec, my_field
            , count(*) over (partition by my_field) as Counter
        from myTable
        where my_field = ?)
    where Counter = 1
    

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 2018-05-17
      • 1970-01-01
      • 2019-07-02
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      相关资源
      最近更新 更多