从mysql表中删除重复的值,但保留一个

时间:2019-02-12 00:54:45

标签: mysql sql

我正在尝试从mysql表中删除重复的行,但仍然保留其中一个。 但是下面的查询似乎删除了每个重复的行,我不确定为什么。基本上,如果outputID,标题和类型都匹配,我想删除该行。

DELETE DupRows.*
FROM output AS DupRows
INNER JOIN (
    SELECT MIN(Output_ID) AS Output_ID, Title, Type
    FROM output
    GROUP BY Title, Type
    HAVING COUNT(*) > 1
) AS SaveRows 
    ON  SaveRows.Title = DupRows.Title 
    AND SaveRows.Type = DupRows.Type
    AND SaveRows.Output_ID = DupRows.Output_ID;

3 个答案:

答案 0 :(得分:1)

刚刚:

DELETE DupRows
FROM output AS DupRows
INNER JOIN output AS SaveRows
    ON  SaveRows.Title = DupRows.Title 
    AND SaveRows.Type = DupRows.Type  
    AND DupRows.Output_ID > SaveRows.Output_ID

这将删除TitleType上的所有重复项,同时使记录保持最低值。

如果运行的是MySQL 8.0,则可以使用窗口函数ROW_NUMBER()来为标题/类型组中的每个记录分配一个按ID排序的等级。然后,您可以删除行号不是1的所有记录。

DELETE FROM output
WHERE Output_ID IN (
    SELECT Output_ID
    FROM (
        SELECT Output_ID, ROW_NUMBER() OVER(PARTITION BY Title, Type ORDER BY Output_ID) rn
        FROM output
    ) x
    WHERE rn > 1
)

答案 1 :(得分:0)

Delete From output  Where Output_ID NOT IN (
Select MIN(Output_ID) from output  Group By Title, Type  Having COUNT(*)>1
)

答案 2 :(得分:0)

在下面的查询中,具有匹配条件的重复行将被删除并保留最旧的唯一行。

注意:-在我的查询中,我使用的id列是自动递增列。

DELETE t1
FROM output  t1, output  t2
WHERE t1.Title  = t2.Title
AND  t1.Type   = t2.Type 
AND t1.Output_ID   = t2.Output_ID 
AND t1.id>t2.id

如果要保留新插入的唯一行,只需将最后一个条件更改为:

DELETE t1
 FROM output  t1, output  t2
 WHERE t1.Title  = t2.Title
 AND  t1.Type   = t2.Type 
 AND t1.Output_ID   = t2.Output_ID 
 AND t1.id<t2.id