Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count duplicates records in Mysql table?

I have table with, folowing structure.

tbl

id   name   1    AAA 2    BBB 3    BBB 4    BBB 5    AAA 6    CCC  select count(name) c from tbl group by name having c >1 

The query returning this result:

AAA(2)  duplicate BBB(3)  duplicate CCC(1)  not duplicate 

The names who are duplicates as AAA and BBB. The final result, who I want is count of this duplicate records.

Result should be like this: Total duplicate products (2)

like image 824
dido Avatar asked Sep 21 '12 10:09

dido


People also ask

How do I find duplicate records in the same table in mysql?

Check for Duplicates in Multiple Tables With INNER JOINUse the INNER JOIN function to find duplicates that exist in multiple tables. Sample syntax for an INNER JOIN function looks like this: SELECT column_name FROM table1 INNER JOIN table2 ON table1. column_name = table2.

How do I SELECT duplicate records in SQL?

To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.


2 Answers

The approach is to have a nested query that has one line per duplicate, and an outer query returning just the count of the results of the inner query.

SELECT count(*) AS duplicate_count FROM (  SELECT name FROM tbl  GROUP BY name HAVING COUNT(name) > 1 ) AS t 
like image 56
xdazz Avatar answered Oct 23 '22 07:10

xdazz


Use IF statement to get your desired output:

SELECT name, COUNT(*) AS times, IF (COUNT(*)>1,"duplicated", "not duplicated") AS duplicated FROM <MY_TABLE> GROUP BY name 

Output:

AAA 2 duplicated BBB 3 duplicated CCC 1 not duplicated 
like image 42
arutaku Avatar answered Oct 23 '22 08:10

arutaku