Finding duplicate values in MySQL

前端 未结 25 2199
执笔经年
执笔经年 2020-11-22 04:04

I have a table with a varchar column, and I would like to find all the records that have duplicate values in this column. What is the best query I can use to find the duplic

相关标签:
25条回答
  • 2020-11-22 04:39
    CREATE TABLE tbl_master
        (`id` int, `email` varchar(15));
    
    INSERT INTO tbl_master
        (`id`, `email`) VALUES
        (1, 'test1@gmail.com'),
        (2, 'test2@gmail.com'),
        (3, 'test1@gmail.com'),
        (4, 'test2@gmail.com'),
        (5, 'test5@gmail.com');
    
    QUERY : SELECT id, email FROM tbl_master
    WHERE email IN (SELECT email FROM tbl_master GROUP BY email HAVING COUNT(id) > 1)
    
    0 讨论(0)
  • 2020-11-22 04:40

    My final query incorporated a few of the answers here that helped - combining group by, count & GROUP_CONCAT.

    SELECT GROUP_CONCAT(id), `magento_simple`, COUNT(*) c 
    FROM product_variant 
    GROUP BY `magento_simple` HAVING c > 1;
    

    This provides the id of both examples (comma separated), the barcode I needed, and how many duplicates.

    Change table and columns accordingly.

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

    I am not seeing any JOIN approaches, which have many uses in terms of duplicates.

    This approach gives you actual doubled results.

    SELECT t1.* FROM my_table as t1 
    LEFT JOIN my_table as t2 
    ON t1.name=t2.name and t1.id!=t2.id 
    WHERE t2.id IS NOT NULL 
    ORDER BY t1.name
    
    0 讨论(0)
  • 2020-11-22 04:40
    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
    
    0 讨论(0)
  • 2020-11-22 04:41

    If you want to remove duplicate use DISTINCT

    Otherwise use this query:

    SELECT users.*,COUNT(user_ID) as user FROM users GROUP BY user_name HAVING user > 1;

    0 讨论(0)
  • 2020-11-22 04:45
    SELECT * 
    FROM `dps` 
    WHERE pid IN (SELECT pid FROM `dps` GROUP BY pid HAVING COUNT(pid)>1)
    
    0 讨论(0)
提交回复
热议问题