Remove duplicate rows in MySQL

前端 未结 25 3493
囚心锁ツ
囚心锁ツ 2020-11-21 04:33

I have a table with the following fields:

id (Unique)
url (Unique)
title
company
site_id

Now, I need to remove rows having same titl

25条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 05:22

    This solution will move the duplicates into one table and the uniques into another.

    -- speed up creating uniques table if dealing with many rows
    CREATE INDEX temp_idx ON jobs(site_id, company, title, location);
    
    -- create the table with unique rows
    INSERT jobs_uniques SELECT * FROM
        (
        SELECT * 
        FROM jobs
        GROUP BY site_id, company, title, location
        HAVING count(1) > 1
        UNION
        SELECT *
        FROM jobs
        GROUP BY site_id, company, title, location
        HAVING count(1) = 1
    ) x
    
    -- create the table with duplicate rows
    INSERT jobs_dupes 
    SELECT * 
    FROM jobs
    WHERE id NOT IN
    (SELECT id FROM jobs_uniques)
    
    -- confirm the difference between uniques and dupes tables
    SELECT COUNT(1)
    AS jobs, 
    (SELECT COUNT(1) FROM jobs_dupes) + (SELECT COUNT(1) FROM jobs_uniques)
    AS sum
    FROM jobs
    

提交回复
热议问题