我正在编写一个 cron 脚本(在 MySQL 数据库的 PHP PDS 中),它将从数据库中删除超过 30 天的数据。我已经尝试在我的表和语句上进行级联和删除,但它们没有奏效,所以我在这里采用了一种更简单的方法来让它工作,但我知道这不是最有效的处理器方法。
请注意,其中一些表(尤其是链接表)有数十万行,这就是为什么我想比这里的表更聪明一点。
表结构很简单,有一个带有时间戳和id的表键表。该 id 在所有表中重复为tablekey_id
.
我目前的 cron 工作如下。
/* Cron script to delete old data from the database. */
if (@include dirname(dirname(dirname(__FILE__))) . '/dbconn/website_connections.php') {
$conn = $connectionFromOtherFile;
$keyTable = 'table_key';
$linksTable = 'links';
$domainsTable = 'link_domains';
$terms = 'searched_domains';
$query = $conn->query("SELECT `id` FROM `$keyTable` WHERE `timestamp` < (NOW() - INTERVAL 30 DAY)");
$query->setFetchMode(PDO::FETCH_ASSOC);
while($row = $query->fetch()) {
$conn->exec("DELETE FROM `$linksTable` WHERE `tablekey_id` = $row[id]");
$conn->exec("DELETE FROM `$domainsTable` WHERE `tablekey_id` = $row[id]");
$conn->exec("DELETE FROM `$terms` WHERE `tablekey_id` = $row[id]");
$conn->exec("DELETE FROM `$keyTable` WHERE `id` = $row[id]");
}
}
有没有办法把它变成一个声明?请并感谢您的帮助。
编辑:继承人我结束了。
/* Cron script to delete old data from the database. */
if (@include dirname(dirname(dirname(__FILE__))) . '/dbconn/website_connections.php') {
$conn = $connectionFromOtherFile;
$keyTable = 'table_key';
$linksTable = 'links';
$domainsTable = 'link_domains';
$terms = 'searched_domains';
$delete = $conn->prepare("DELETE tablekey, linktable, domaintable, searched
FROM `$keyTable` AS tablekey
LEFT OUTER JOIN `$linksTable` AS linktable on tablekey.id = linktable.tablekey_id
LEFT OUTER JOIN `$domainsTable` AS domaintable on tablekey.id = domaintable.tablekey_id
LEFT OUTER JOIN `$terms` AS searched on tablekey.id = searched.tablekey_id
WHERE tablekey.id = :tablekey_id");
$query = $conn->query("SELECT `id` FROM `$keyTable` WHERE `timestamp` < (NOW() - INTERVAL 30 DAY)");
$query->setFetchMode(PDO::FETCH_ASSOC);
while($row = $query->fetch()) {
$delete->execute(array('tablekey_id' => $row['id']));
}
}