Remove duplicate rows in MySQL

前端 未结 25 3492
囚心锁ツ
囚心锁ツ 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:10

    If you don't want to alter the column properties, then you can use the query below.

    Since you have a column which has unique IDs (e.g., auto_increment columns), you can use it to remove the duplicates:

    DELETE `a`
    FROM
        `jobs` AS `a`,
        `jobs` AS `b`
    WHERE
        -- IMPORTANT: Ensures one version remains
        -- Change "ID" to your unique column's name
        `a`.`ID` < `b`.`ID`
    
        -- Any duplicates you want to check for
        AND (`a`.`title` = `b`.`title` OR `a`.`title` IS NULL AND `b`.`title` IS NULL)
        AND (`a`.`company` = `b`.`company` OR `a`.`company` IS NULL AND `b`.`company` IS NULL)
        AND (`a`.`site_id` = `b`.`site_id` OR `a`.`site_id` IS NULL AND `b`.`site_id` IS NULL);
    

    In MySQL, you can simplify it even more with the NULL-safe equal operator (aka "spaceship operator"):

    DELETE `a`
    FROM
        `jobs` AS `a`,
        `jobs` AS `b`
    WHERE
        -- IMPORTANT: Ensures one version remains
        -- Change "ID" to your unique column's name
        `a`.`ID` < `b`.`ID`
    
        -- Any duplicates you want to check for
        AND `a`.`title` <=> `b`.`title`
        AND `a`.`company` <=> `b`.`company`
        AND `a`.`site_id` <=> `b`.`site_id`;
    

提交回复
热议问题