在实时数据库上运行之前仔细阅读代码

时间:2013-09-02 07:12:45

标签: mysql archive sql-delete

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

以下是代码:

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个月的归档列表需要完全删除。

我认为我已经以最强大的方式完成了这项工作,但如果我错过了什么,我会批评吗?

0 个答案:

没有答案