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
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.
To check for duplicates in MySQL, you can use group by having clause. The syntax is as follows. select yourColumnName1,yourColumnName2,......
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.
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With