我正在從數據庫中刪除超過30天的數據的cron腳本(在PHP PDS中爲MySQL數據庫)。我試圖加入和刪除級聯我的表和聲明,但他們沒有解決,所以我在這裏採取了一個更簡單的方法來讓它工作,但我知道這不是最有效的處理器方法。跨多個表的MySQL刪除
請注意,這些表中的一些(特別是鏈接表)有成千上萬的行,所以這就是爲什麼我想比我在這裏更聰明一些。
表結構很簡單,有一個表的關鍵表,有一個時間戳和一個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']));
}
}
你有考慮外鍵和級聯刪除嗎? – 2013-02-21 16:22:42
爲什麼使用PDO構建查詢字符串?它支持預處理語句,它在循環中具有性能優勢,並且不易受SQL注入的影響 – GordonM 2013-02-21 16:22:57
可能重複[Mysql - 使用一個查詢從多個表中刪除](http://stackoverflow.com/questions/4839905/mysql-delete -from-multiple-tables-with-one-query) – 2013-02-21 16:23:09