基于mysql表中的另一列查找表中两列的重复项

基于mysql表中的另一列查找表中两列的重复项,mysql,sql,count,subquery,Mysql,Sql,Count,Subquery,我有一张桌子可以储存电话号码 电话号码 -------------------------------- id | primary | phone1 | phone2 | -------------------------------- 1 | phone1 | xxx | xxx | 2 | phone2 | xxx | xxx | 3 | phone2 | xxx | xxx | 4 | phone1 | xxx | x

我有一张桌子可以储存电话号码

电话号码

--------------------------------
id | primary | phone1 | phone2  |
--------------------------------
1  | phone1  |  xxx   |  xxx    |
2  | phone2  |  xxx   |  xxx    | 
3  | phone2  |  xxx   |  xxx    | 
4  | phone1  |  xxx   |  xxx    |
5  | phone2  |  xxx   |  xxx    |
6  | phone1  |  xxx   |  xxx    |
如何从表中找到主电话号码的重复条目(以及相应的记录)?如果primary为phone1,则值存储在phone1中,如果primary为phone2,则值存储在phone2字段中

如何从表中找到主电话号码的重复条目(以及相应的记录)

如果要显示整个原始记录,最简单的选项可能是
exists
和条件表达式:

select t.*
from mytable t
where exists (
    select 1 
    from mytable t1
    where 
        case when t1.primary = 'phone1' then t1.phone1 else t1.phone2 end
            = case when t.primary = 'phone1' then t.phone1 else t.phone2 end
        and t1.id <> t.id
)
如何从表中找到主电话号码的重复条目(以及相应的记录)

如果要显示整个原始记录,最简单的选项可能是
exists
和条件表达式:

select t.*
from mytable t
where exists (
    select 1 
    from mytable t1
    where 
        case when t1.primary = 'phone1' then t1.phone1 else t1.phone2 end
            = case when t.primary = 'phone1' then t.phone1 else t.phone2 end
        and t1.id <> t.id
)

您应该修复数据模型并将手机存储在单独的行中。如果没有,您可以取消PIVOT并聚合以在不同列中查找数字: 以下内容返回所有多次出现的手机以及存储手机的列:

select phone, sum(is_primary) as num_primary, sum(is_1) as num_1, num(is_2) asnum2
from ((select primary as phone, 1 as is_primary, 0 as is_1, 0 as is_2
       from phone_numbers pn
      ) union all
      (select phone1, 0 as is_primary, 1 as is_1, 0 as is_2
       from phone_numbers pn
      ) union all
      (select phon2, 0 as is_primary, 0 as is_1, 1 as is_2
       from phone_numbers pn
      ) 
     ) t
where phone is not null
group by phone
having count(*) > 1;

您应该修复数据模型并将手机存储在单独的行中。如果没有,您可以取消PIVOT并聚合以在不同列中查找数字: 以下内容返回所有多次出现的手机以及存储手机的列:

select phone, sum(is_primary) as num_primary, sum(is_1) as num_1, num(is_2) asnum2
from ((select primary as phone, 1 as is_primary, 0 as is_1, 0 as is_2
       from phone_numbers pn
      ) union all
      (select phone1, 0 as is_primary, 1 as is_1, 0 as is_2
       from phone_numbers pn
      ) union all
      (select phon2, 0 as is_primary, 0 as is_1, 1 as is_2
       from phone_numbers pn
      ) 
     ) t
where phone is not null
group by phone
having count(*) > 1;