8

我有一张桌子:

| foo | bar |
+-----+-----+
| a   | abc |
| b   | def |
| c   | ghi |
| d   | jkl |
| a   | mno |
| e   | pqr |
| c   | stu |
| f   | vwx |

我想按列删除所有包含重复项的行,foo以便表格如下所示:

| foo | bar |
+-----+-----+
| b   | def |
| d   | jkl |
| e   | pqr |
| f   | vwx |

最有效的方法是什么?

4

2 回答 2

10

foo您可以使用仅返回唯一的子查询连接表LEFT JOIN。子查询中没有匹配的行将根据需要删除,例如

DELETE  a
FROM    TableName a
        LEFT JOIN
        (
            SELECT  foo
            FROM    TableName
            GROUP   BY Foo
            HAVING  COUNT(*) = 1
        ) b ON a.Foo = b.Foo
WHERE   b.Foo IS NULL

为了获得更快的性能,请在 column 上添加索引Foo

ALTER TABLE tableName ADD INDEX(foo)
于 2013-04-07T17:25:52.190 回答
8

使用EXISTS

DELETE a
  FROM TableName a
 WHERE EXISTS (SELECT NULL
                 FROM TableName b
                WHERE b.foo = a.foo
             GROUP BY b.foo
               HAVING COUNT(*) > 1)

使用IN

DELETE a
  FROM TableName a
 WHERE a.foo IN (SELECT b.foo
                   FROM TableName b
               GROUP BY b.foo
                 HAVING COUNT(*) > 1)
于 2013-04-08T03:40:10.517 回答