Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL List All Duplicates [duplicate]

Possible Duplicate:
Find duplicate records in MySQL

I have a table in MySQL like this:

ID    name    email
1    john     [email protected]
2    johnny   [email protected]
3    jim      [email protected]
4    Michael  [email protected]

How can I have the MySQL query that will list out the duplicate one like this?

Result of duplicate search:

ID    name    email         Duplicate
1    john     [email protected]      2
2    johnny   [email protected]      2
like image 648
user1995781 Avatar asked Jan 21 '13 02:01

user1995781


People also ask

How do I find duplicate values in MySQL?

Find duplicate values in one column First, use the GROUP BY clause to group all rows by the target column, which is the column that you want to check duplicate. Then, use the COUNT() function in the HAVING clause to check if any group have more than 1 element. These groups are duplicate.

How do I find duplicate values in two columns in MySQL?

To check for duplicates in MySQL, you can use group by having clause. The syntax is as follows. select yourColumnName1,yourColumnName2,......

Can MySQL have duplicate rows?

MySQL is a database application that stores data in tables in the form of rows and columns. This database application can store duplicate records in the table, which can impact the performance of the database in MySQL.


2 Answers

SELECT  a.*, b.totalCount AS Duplicate
FROM    tablename a
        INNER JOIN
        (
            SELECT  email, COUNT(*) totalCount
            FROM    tableName
            GROUP   BY email
        ) b ON a.email = b.email
WHERE   b.totalCount >= 2
  • SQLFiddle Demo

for better performance, add an INDEX on column EMail.

OR

SELECT  a.*, b.totalCount AS Duplicate
FROM    tablename a
        INNER JOIN
        (
            SELECT  email, COUNT(*) totalCount
            FROM    tableName
            GROUP   BY email
            HAVING  COUNT(*) >= 2
        ) b ON a.email = b.email
  • SQLFiddle Demo
like image 60
John Woo Avatar answered Sep 17 '22 17:09

John Woo


If you can live with having the ID and name in comma separated lists, then you can try:

select email, count(*) as numdups,
       group_concat(id order by id), group_concat(name order by id)
from t
group by email
having count(*) > 1

This saves a join, although the result is not in a relational format.

like image 27
Gordon Linoff Avatar answered Sep 21 '22 17:09

Gordon Linoff