在没有命名列的MySQL中查找重复记录

时间:2014-04-27 22:06:20

标签: mysql sql

我有一张这样的表:

**lead_id** **form_id** **field_number** **value**

1           2           1                Richard
1           2           2                Garriot

2           2           1                Hellen
2           2           2                Garriot

3           2           1                Richard
3           2           2                Douglas

4           2           1                Tomas
4           2           2                Anderson

其中field_number = 1是姓名,field_number = 2是姓氏。

我想找到名称或姓氏相同的条目,并将它们按lead_id分组,因此输出可能是这样的:

1
2
3

有关如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:0)

Select leadid from (
Select DISTINCT leadid,value from tablename
Where fieldnumber=1
Group by leadid,value
Having count(value) >1
Union all
Select DISTINCT leadid,value from tablename
Where fieldnumber=2
Group by leadid,value
Having count(value) >1
) as temp

肯定有更快的选择

答案 1 :(得分:0)

这应该有效并且相当有效(取决于索引):

select distinct lead_id
from tablename as t1
where exists (
  select 1
  from tablename as t2
  where t1.field_number = t2.field_number
  and   t1.value = t2.value 
  and   t1.lead_id <> t2.lead_id 
  )