如何从MySQL中select删除?

这个代码不适用于MySQL 5.0,如何重写它使其工作

DELETE FROM posts where id=(SELECT id FROM posts GROUP BY id HAVING ( COUNT(id) > 1 )) 

我想删除没有唯一ID的列。 我会补充说,大部分时间里只有一个id(我尝试过在语法上,而且它不工作)。

SELECT (子)查询返回结果 。 所以你需要使用IN ,而不是在你的WHERE子句中。

此外, 如此答案中所示,不能从同一查询中的子查询中修改相同的表。 但是,您可以在单独的查询中SELECT然后DELETE ,也可以嵌套另一个子查询和别名内部子查询结果(尽pipe如此,看起来相当黑客):

 DELETE FROM posts WHERE id IN ( SELECT * FROM ( SELECT id FROM posts GROUP BY id HAVING ( COUNT(id) > 1 ) ) AS p ) 

或者使用Mchlbuild议的连接 。

 DELETE p1 FROM posts AS p1 CROSS JOIN ( SELECT ID FROM posts GROUP BY id HAVING COUNT(id) > 1 ) AS p2 USING (id) 

你可以使用内部连接:

 DELETE ps FROM posts ps INNER JOIN (SELECT distinct id FROM posts GROUP BY id HAVING COUNT(id) > 1 ) dubids on dubids.id = ps.id 

如果您想删除所有重复项,但每个重复项中只有一个重复项,则这是一个解决scheme:

 DELETE posts FROM posts LEFT JOIN ( SELECT id FROM posts GROUP BY id HAVING COUNT(id) = 1 UNION SELECT id FROM posts GROUP BY id HAVING COUNT(id) != 1 ) AS duplicate USING (id) WHERE duplicate.id IS NULL;