I want to pull out duplicate records in a MySQL Database. This can be done with:
SELECT address, count(id) as cnt FROM list
GROUP BY address HAVING cnt > 1
Which results in:
100 MAIN ST 2
I would like to pull it so that it shows each row that is a duplicate. Something like:
JIM JONES 100 MAIN ST
JOHN SMITH 100 MAIN ST
Any thoughts on how this can be done? I'm trying to avoid doing the first one then looking up the duplicates with a second query in the code.
Why not just INNER JOIN the table with itself?
A DISTINCT is needed if the address could exist more than two times.
This will select duplicates in one table pass, no subqueries.
This query actially emulates
ROW_NUMBER()
present inOracle
andSQL Server
See the article in my blog for details:
MySQL
.Another solution would be to use table aliases, like so:
All you're really doing in this case is taking the original list table, creating two pretend tables -- p1 and p2 -- out of that, and then performing a join on the address column (line 3). The 4th line makes sure that the same record doesn't show up multiple times in your set of results ("duplicate duplicates").