我有一个表有很多重复记录,即tbl_voter,ID为主键,自动增量。还有另一个表tbl_notes,它为每个选民记录了一些信息。 tbl_notes可以有每个选民零或更多的记录。来自tbl_voter的ID是tbl_notes中的外键。查找重复记录的ID sql
问题是因为在选举人表中有重复,在笔记表中也有重复。
例如: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
我想找到与原有的所有ID和它们的副本,以便更新tbl_notes
例如: 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不能在group by查询中使用这是正确的,因为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,我可以更新tbl_notes。
感谢, 沙善
我不记得确切的语法,但我认为'GROUP_CONCAT'可以用来给所有的ID,其中的行,列=行,通过搜索 – andrew
@andrew列ID开始group_concat不适用于MSSQL。我试图寻找替代品,但它基本上建议将ID分组,而不是重复的。我需要重复的,以便在这两个表中更新它们 – Shashank