How to delete a table row if the field “post_title” is duplicated in another row? [duplicate]

你。 提交于 2019-12-11 23:59:37

问题


Possible Duplicate:
Remove Duplicate Rows Leaving Oldest Row Only?

I have a posts_table in my DB.. That posts_table have the fields post_title, post_id, (and some others that dont matter).

I need to delete one of the rows if the post_title repeats in another row.

Example:

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

With the sentence below i can check all duplicated post_titles

SELECT    post_title, COUNT(post_title) AS dup_count
FROM      posts_table
GROUP BY  post_title
HAVING    (COUNT(post_title) > 1) 

The question is, How can i delete all rows with duplicated post_titles??

The best and fastest query for this is:

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
)

回答1:


try this one:

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
    )


来源:https://stackoverflow.com/questions/9196884/how-to-delete-a-table-row-if-the-field-post-title-is-duplicated-in-another-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!