【问题标题】:sql select only duplicate rowssql只选择重复的行
【发布时间】:2021-03-24 19:41:37
【问题描述】:

我在数据库中有一个表

username, ip 
A       , ipA1
A       , ipA1
B       , ipB1
A       , ipA1
C       , ipC1
A       , ipA2
C       , ipC2

我需要提取具有不同不同 ip 的同一用户的所有行

即结果:

username, ip 
A       , ipA1
C       , ipC1
A       , ipA2
C       , ipC2

【问题讨论】:

  • MySQL 还是 Oracle 数据库?你用两者都标记了你的问题。如果您需要一个适用于两者的解决方案,您应该在问题中明确说明。如果实际上您只使用两者之一,请确保您的标签反映了这一点。

标签: mysql sql oracle


【解决方案1】:

一种方法是exists:

select distinct username, ip
from t
where exists (select 1 from t t2 where t2.username = t.username and t2.ip <> t.ip);

【讨论】:

    【解决方案2】:
    with
      my_table (username, ip) as (
        select 'A', 'ipA1' from dual union all
        select 'A', 'ipA1' from dual union all
        select 'B', 'ipB1' from dual union all
        select 'A', 'ipA1' from dual union all
        select 'C', 'ipC1' from dual union all
        select 'A', 'ipA2' from dual union all
        select 'C', 'ipC2' from dual
      )
    select distinct username, ip
    from   (
             select username, ip,
                    min(ip) over (partition by username) as min_ip,
                    max(ip) over (partition by username) as max_ip
             from   my_table
           )
    where min_ip != max_ip
    ;
    
    
    USERNAME IP  
    -------- ----
    A        ipA2
    C        ipC1
    C        ipC2
    A        ipA1
    

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-12
      • 1970-01-01
      • 2020-10-16
      • 2011-12-06
      • 1970-01-01
      • 2020-07-27
      相关资源
      最近更新 更多