drwg89980 2015-10-08 16:08
浏览 33
已采纳

删除MySQL中的重复行(Wordpress,评论)

I have a plethora of duplicate comments in my Wordpress database, specifically table wp_comments. Of course, those comments have a different IDs. I'd now like to de-dupe those comments based on the field comment_date which would identify all comments posted on the same date and time. I don't care which one of the duplicates remain.

What SQL query do I have to use to achieve this?

Thanks!

EDIT: I don't want to delete a specific comment date across the table, instead I want the database to scan for duplicate dates and remain with only one entry.

  • 写回答

2条回答 默认 最新

  • duanpoqiu0919 2015-10-08 16:15
    关注

    You could do a select all query and then loop through those. While in the loop do a query that delete anything that is the same and doesn't have the ID of current index. Backup first.

    Update:

    I prefer to keep this kind of code in a separate file in the root directory.

    SO make a new file in root and call it whatever you want and then add this code. Run the file AFTER YOU BACKUP your comment and comment meta tables.

    You could do a select all query and then loop through those. While in the loop do a query that  delete anything that is the same and doesn't have the ID of current index. Backup first.
    

    Update:

    I prefer to keep this kind of code in a separate file in the root directory.

    SO make a new file in root and call it whatever you want and then add this code. Run the file AFTER YOU BACKUP your comment and comment meta tables.

    <?php 
    require('./wp-load.php');
    global $wpdb; // loads the DB object
    
    $comments = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."comments");
    
    foreach((array)$comments as $key => $comment)
    {
        $id_to_check = $comment->comment_ID; // keep this comment ID
        $get_dupes = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."comments WHERE comment_content = '".$comment->comment_content."' AND comment_ID != $id_to_check OR comment_date = '".$comment->comment_date."' AND comment_ID != '".$id_to_check."' ");
    
        foreach((array)$get_dupes as $dkey => $dupe)
        {
             $wpdb->query("DELETE FROM ".$wpdb->prefix."commentmeta WHERE comment_id = '".$dupe->comment_ID."'"); // delete duplicate comment meta
        }
    
        $wpdb->query("DELETE FROM ".$wpdb->prefix."comments WHERE comment_ID = '".$dupe->comment_ID."'"); // delete duplicate comment
    
    }
    echo 'all done!'
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据