I have a table which has lots of duplicate records namely tbl_voter with ID as primary key, auto increment. and there is another table tbl_notes which has notes for each voter. tbl_notes can have zero or more records of each voter. The ID from tbl_voter is the foreign key in the tbl_notes.
The problem is since there are duplicates in the voter table, there are duplicates in notes table as well.
For Example: tbl_voter
ID Name Address
01 abc xyz
02 def pqr
03 abc xyz
04 abc xyz
05 abc xyz
06 def pqr
tbl_notes
Noteid ID Note
A001 01 aaaaaa
A002 02 bbbbbb
A003 01 cccccc
A004 03 dddddd
A005 03 eeeeee
A006 04 ffffff
A007 05 gggggg
A008 01 hhhhhh
I want to find all the IDs of the original ones and their duplicates so as to update the tbl_notes
For Example: tbl_voter
ID Name Address
01 abc xyz
02 def pqr
tbl_notes
Noteid ID Note
A001 01 aaaaaa
A002 02 bbbbbb
A003 01 cccccc
A004 01 dddddd
A005 01 eeeeee
A006 01 ffffff
A007 01 gggggg
A008 01 hhhhhh
So far I have tried to find the duplicate records but it gives me the original ones as well as the duplicate ones. I need a query which returns me:
RealID DuplicateID
01 03
01 04
01 05
02 06
The Query I tried :
select *
from tbl_voter a inner join
(
select id,firstname,lastname,zip,housenumber,COUNT(*) AS dupes from tbl_voter
where riding = '35019'
group by
firstname,lastname,zip,housenumber
having count(*) > 1
) b on a.firstname = b.firstname
and a.lastname = b.lastname
and a.zip = b.zip
and a.firstname is not null
and b.firstname is not null
and a.riding='35019'
and a.housenumber=b.housenumber
order by a.firstname asc
If i add ID into the select query, it throws an error saying ID cannot be used in the group by query which is right as IDs will be different all the time.
The query with the IDs taken into consideration:
select a.id as realid, b.id as dupid, a.firstname,a.lastname,a.zip,a.housenumber
from tbl_voter a inner join
(
select id,firstname,lastname,zip,housenumber,COUNT(*) AS dupes from tbl_voter
where riding = '35019'
group by
id,firstname,lastname,zip,housenumber
having count(*) > 1
) b on a.firstname = b.firstname
and a.lastname = b.lastname
and a.zip = b.zip
and a.firstname is not null
and b.firstname is not null
and a.riding='35019'
and a.housenumber=b.housenumber
order by a.firstname asc
If i get the IDs which are duplicates and the real ones, I can update the tbl_notes.
Thanks, Shashank
GROUP_CONCAT
can be used to give all the ids where row,column= row,column id start by searching for that