ID が主キーの自動インクリメントである tbl_voter という重複レコードが多数あるテーブルがあります。また、各有権者のメモを持つ別のテーブル tbl_notes があります。tbl_notes には、各有権者の 0 個以上のレコードを含めることができます。tbl_voter からの ID は、tbl_notes の外部キーです。
問題は、voter テーブルに重複があるため、notes テーブルにも重複があることです。
例: 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
tbl_notes を更新するために、元の ID とその複製のすべての ID を検索したい
例: 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
これまでのところ、重複レコードを見つけようとしましたが、元のレコードと重複レコードが表示されます。私を返すクエリが必要です:
RealID DuplicateID
01 03
01 04
01 05
02 06
私が試したクエリ:
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
選択クエリにIDを追加すると、IDが常に異なるため、クエリによるグループではIDを使用できないというエラーがスローされます。
ID を考慮したクエリ:
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
重複する ID と実際の ID が分かれば、tbl_notes を更新できます。
ありがとう、シャシャンク