【问题标题】:Find duplicates from two columns in a table based on another column in a mysql table根据mysql表中的另一列从表中的两列中查找重复项
【发布时间】:2021-03-29 08:46:59
【问题描述】:
我有一张桌子来存储电话号码
电话号码
--------------------------------
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,则 value 存储在 phone1 中,如果 primary 是 phone2,则 value 存储在 phone2 字段中
【问题讨论】:
标签:
mysql
sql
count
subquery
【解决方案1】:
如何从表中找到主要电话号码的重复条目(和相应记录)?
如果要显示整个原始记录,最简单的选项可能是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
)
在 MySQL 8.0 中,另一种方法使用窗口计数:
select *
from (
select t.*,
count(*) over(partition by case when primary = 'phone1' then phone1 else phone2 end) as cnt
from mytable t
) t
where cnt > 1
【解决方案2】:
您应该修复您的数据模型并将电话存储在单独的行上。如果没有,您可以反透视和聚合以查找不同列中的数字:
以下返回所有出现多次的电话以及电话所在的列:
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;