Find duplicate records in MySQL

后端 未结 23 2849
别跟我提以往
别跟我提以往 2020-11-21 23:12

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 >         


        
相关标签:
23条回答
  • 2020-11-22 00:03
    select `cityname` from `codcities` group by `cityname` having count(*)>=2
    

    This is the similar query you have asked for and its 200% working and easy too. Enjoy!!!

    0 讨论(0)
  • 2020-11-22 00:04

    Another solution would be to use table aliases, like so:

    SELECT p1.id, p2.id, p1.address
    FROM list AS p1, list AS p2
    WHERE p1.address = p2.address
    AND p1.id != p2.id
    

    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").

    0 讨论(0)
  • 2020-11-22 00:04

    This will select duplicates in one table pass, no subqueries.

    SELECT  *
    FROM    (
            SELECT  ao.*, (@r := @r + 1) AS rn
            FROM    (
                    SELECT  @_address := 'N'
                    ) vars,
                    (
                    SELECT  *
                    FROM
                            list a
                    ORDER BY
                            address, id
                    ) ao
            WHERE   CASE WHEN @_address <> address THEN @r := 0 ELSE 0 END IS NOT NULL
                    AND (@_address := address ) IS NOT NULL
            ) aoo
    WHERE   rn > 1
    

    This query actially emulates ROW_NUMBER() present in Oracle and SQL Server

    See the article in my blog for details:

    • Analytic functions: SUM, AVG, ROW_NUMBER - emulating in MySQL.
    0 讨论(0)
  • 2020-11-22 00:05

    I tried the best answer chosen for this question, but it confused me somewhat. I actually needed that just on a single field from my table. The following example from this link worked out very well for me:

    SELECT COUNT(*) c,title FROM `data` GROUP BY title HAVING c > 1;
    
    0 讨论(0)
  • 2020-11-22 00:05
    SELECT t.*,(select count(*) from city as tt where tt.name=t.name) as count FROM `city` as t where (select count(*) from city as tt where tt.name=t.name) > 1 order by count desc
    

    Replace city with your Table. Replace name with your field name

    0 讨论(0)
提交回复
热议问题