我的数据库中有posts_table
..
posts_table包含字段post_title
,post_id
,(以及其他一些不重要的字段)。
如果post_title在另一行重复,我需要删除其中一行。
示例:
posts_table
-------------------------------------------
post_id | post_title
-------------------------------------------
501 | Some post title here
502 | Another post title
503 | A test post tile
504 | Some post title here (this is duplicated, i need to delete this row)
505 | A different post title
使用下面的句子,我可以检查所有重复的post_titles
SELECT post_title, COUNT(post_title) AS dup_count
FROM posts_table
GROUP BY post_title
HAVING (COUNT(post_title) > 1)
问题是,如何删除所有具有重复post_titles的行?
最好和最快的查询是:
delete from posts_table where post_id in (
select post_id from (
select post_id from posts_table a group by post_title having count(post_title) > 1
) b
)
答案 0 :(得分:2)
试试这个:
DELETE FROM Posts_Table
WHERE Post_ID NOT IN
(
SELECT a.Post_ID
FROM
(
SELECT Post_Title, Post_ID
FROM Posts_Table
GROUP BY Post_Title
) a
)