0

我有一个需要尽快清理的笨重数据库的客户。我已经在不影响他的数据库服务器性能的情况下完成了所有测试,但是当我们谈论需要移动/删除的数百万条记录时,我无法轻松创建测试环境。

这是代码:

ini_set('memory_limit', '-1');
ini_set('set_time_limit', '0');
ini_set('max_execution_time', '0');


/* 
* Main Database Maint. 
*/

//connect to db
$db = new PDO('mysql:host=xxxxxx;dbname=xxxxx;charset=utf8', 'xxxx', 'xxxxxx');

// move listings to archive if over 1 month old
print "Copying items older than 1 month to archive\n";
$db->query("INSERT INTO `listing_archived` SELECT * FROM `listing` WHERE `dateadd` < DATE_SUB(CURDATE( ), INTERVAL 1 MONTH)");

// delete listings from main database that meet same criteria
print "Deleting items from main database\n";
$db->query("DELETE FROM `listing` WHERE `dateadd` < DATE_SUB(CURDATE( ), INTERVAL 1 MONTH)");

// optimize the table as we are expecting lots of deletes
print "Optimizing main database table\n";
$db->query("OPTIMIZE TABLE `listing`");


/*
* Archive database maint.
*/

// Select anything older than 3 months from archive table
$q = $db->query("SELECT * FROM `listing_archive` WHERE `dateadd` < DATE_SUB(CURDATE(), INTERVAL 3 MONTH)");

while ($r = $q->fetch(PDO::FETCH_ASSOC))
{
    //unlink images related to this item
    print "Deleting images linked to item {$r['id']}\n";


    // delete item from database
    print "Deleting database record {$r['id']}\n";  
    $db->query("DELETE FROM listing_archive WHERE id = {$r['id']}");
}

评论应该让您了解所需的内容。列表中超过 1 个月的项目需要移动到 Listing_archive。然后超过 3 个月的存档列表需要完全删除。

我认为我已经以最强大的方式完成了它,但如果我错过了什么,我愿意接受批评?

4

0 回答 0