MySQL,删除重复的行(必须是2列唯一的)

时间:2016-07-14 08:26:35

标签: php mysql

我有这个:

1899, 184, 531 *
1900, 184, 531 *
1901, 113, 531
1902, 184, 436

我想要

1899, 184, 531
1901, 113, 531
1902, 184, 436

没有临时表等。如何?

6 个答案:

答案 0 :(得分:5)

SELECT MIN(Col1), Col2, Col3
FROM yourTable
GROUP BY Col2, Col3

这假设您选择了1899以上的1900记录,因为前者是两者中较小的一个。

如果您想从表中删除重复记录(因为您已将它们定义为重复记录),则可以使用以下查询:

DELETE t1.*
FROM yourTable t1
LEFT JOIN
(
    SELECT MIN(Col1) AS Col1, Col2, Col3
    FROM yourTable
    GROUP BY Col2, Col3
) t2
    ON t1.Col1 = t2.Col1 AND t1.Col2 = t2.Col2 AND t1.Col3 = t2.Col3
WHERE t2.Col1 IS NULL

答案 1 :(得分:1)

select min(f1) as f1, f2, f3 from tbl group by f2, f3

答案 2 :(得分:1)

如果要在过滤掉重复项的位置进行SELECT,可以使用:

SELECT DISTINCT Col2, Col3 FROM table_name ORDER BY Id;

SQL fiddle for SELECT

或者,如果您想要DELETE查询,可以执行以下操作:

DELETE t1 FROM table_name t1, table_name t2
WHERE t1.Id < t2.Id
AND t1.Col2 = t2.Col2 
AND t1.Col3 = t2.Col3;

SQL fiddle for DELETE

答案 3 :(得分:1)

对于DELETE:

DELETE
FROM table1 t
WHERE EXISTS (SELECT u.*
              FROM table1 u
              WHERE u.col2 = t.col2 AND u.col3 = t.col3
              AND u.col1 > t.col1)

当然存在与子查询在同一个表上删除的问题。

答案 4 :(得分:1)

DELETE

DELETE t1
FROM yourtable t1
JOIN yourtable t2
ON t1.col2 = t2.col2
AND t1.col3 = t2.col3
AND t1.col1 > t2.col1

SQLFiddle Demo

答案 5 :(得分:0)

这可以删除重复的行。

从table_name中删除column1 in(select column1 from(select column1 from table_name group by column1,column2 having count(*)&gt; 1)t);