如何删除重复的行将两列分组?

时间:2019-02-08 02:54:28

标签: mysql sql database mysqli

我的数据库中有一个表(婴儿名字),其中有重复的记录要删除。

我的表中的Ex记录

id category_id  baby_name   url_role    
1      6        karthik     karthik    
2      7        kalaivanan  kalaivanan    
3      4        arun        arun    
4      6        vijayakumar vijayakumar    
5      6        karthik     karthik    
6      6        karthik     karthik    
7      4        karthik     karthik
9      6        vijayakumar vijayakumar    
8      4        karthik     karthik

我需要结果

id category_id  baby_name   url_role    
1      6        karthik     karthik    
2      7        kalaivanan  kalaivanan    
3      4        arun        arun    
4      6        vijayakumar vijayakumar    
7      4        karthik     karthik

我需要删除在相同类别中找到的具有相同baby_name的重复记录。我不想为此创建具有不同条目的新表。我需要从现有表中删除重复的条目,而无需创建任何新表。

  DELETE FROM babynames 
   WHERE id NOT IN 
                  (   SELECT MIN(id)  
                        FROM babynames 
                    GROUP BY baby_name,category_id
                  )

4 个答案:

答案 0 :(得分:0)

在MySQL中,您应该使用JOIN

DELETE b
    FROM babynames b LEFT JOIN
         (SELECT baby_name, category_id, MIN(id) as min_id
          FROM babynames 
          GROUP BY baby_name,category_id
         ) bb
         ON bb.min_id = b.id
    WHERE bb.min_id IS NULL;

答案 1 :(得分:0)

您可以使用EXISTS子句,注意将内部FROM包装到子查询中,以避免出现可怕的问题

  

您不能在FROM子句中指定要更新的目标表'x'

错误:

DELETE b
FROM babynames b
WHERE EXISTS (SELECT * 
              FROM (SELECT * FROM babynames) b1 
              WHERE b1.category_id = b.category_id
                AND b1.baby_name = b.baby_name
                AND b1.id < b.id)

输出:

id  category_id     baby_name       url_role
1   6               karthik         karthik
2   7               kalaivanan      kalaivanan
3   4               arun            arun
4   6               vijayakumar     vijayakumar
7   4               karthik         karthik

Demo on dbfiddle

答案 2 :(得分:0)

要从表中删除重复的记录,您可以按以下步骤操作

delete from names 
where id not in 
(
select min(id)
from names 
group by category_id,baby_name,url_role 

  )

答案 3 :(得分:0)

  

请尝试

 DELETE FROM babynames 
   WHERE id   IN 
                  (  
                  select id from (SELECT id ,  RANK() OVER (PARTITION BY baby_name,category_id
                 ORDER BY  sale DESC  )rw sales_rank FROM babynames)t1 where rw>1
                  )