MySQL删除重复的记录,但保留多个(例如5)

时间:2019-05-20 14:20:04

标签: mysql

我有一个包含多个重复记录的表,并且我想根据特定编号(例如10个重复记录中的3个或5个)删除其中一些记录。如何在MySQL中实现呢?

记录示例:

ID           TEXT
1000         HELLO JOHN
1001         HELLO JOHN
1002         HELLO JOHN
1003         HELLO JOHN      
1004         HELLO JOHN
1005         HELLO JOHN
1006         HELLO JOHN
1007         HELLO JOHN
1008         HELLO JOHN
1009         HELLO JOHN
ETC...

如果我以升序或降序删除,对我来说不会导入。我只想以受控方式删除记录(例如3条记录,5条记录,10条记录等)

我希望例如具有以下输出(以升序模式)

ID           TEXT
1000         HELLO JOHN
1001         HELLO JOHN
1002         HELLO JOHN
1003         HELLO JOHN
1004         HELLO JOHN

3 个答案:

答案 0 :(得分:2)

尝试此查询

DELETE t_n
FROM 
       table_name AS t_n
   JOIN
       ( SELECT id 
         FROM table_name
         WHERE text='HELLO JOHN'
         ORDER BY id       
           LIMIT 5
       ) AS lim
     ON t_n.id > lim.id;

答案 1 :(得分:0)

我的猜测是您有多个文本重复而不仅仅是HELLO JOHN

因此,您可以使用会话变量来模拟ROW_NUMBER() OVER ( PARTITION ...

SQL DEMO

DELETE FROM Table1
WHERE `ID` NOT IN ( 
                    SELECT `ID`
                    FROM (
                            SELECT `ID`,        
                                   @rn:= if (@text = `TEXT`, 
                                             @rn+1, 
                                             if(@text := `TEXT`,1,1)
                                            ) as rn       
                            FROM Table1
                            CROSS JOIN ( SELECT @rn := 0 , @text := '') as vars
                            ORDER BY `ID` 
                          ) as t
                    WHERE rn <=5                        
                  );

答案 2 :(得分:0)

我认为最简单的查询方法是。

DELETE FROM Table1 
WHERE ID NOT IN(
  SELECT 
   a.ID
  FROM (
    SELECT 
     ID 
    FROM 
     Table1
    ORDER BY 
     Table1.ID ASC
    LIMIT 5
  ) AS a
)

请参阅demo

因为你做不到

DELETE FROM Table1 
WHERE ID NOT IN(
    SELECT 
     ID 
    FROM 
     Table1
    ORDER BY 
     Table1.ID ASC
    LIMIT 5
)

因为它错误

  

此版本的MySQL尚不支持'LIMIT&IN / ALL / ANY / SOME   子查询”

请参阅demo