這是我能想到做到這一點的唯一方法,並且我得到了關於限制的錯誤。我試圖在while循環內以塊的形式刪除,因爲結果總數可能相當大。mysql刪除內部連接和限制
第一個計數語句正常工作。它是第二個,刪除語句,沒有。我猜是因爲連接和/或使用限制。我仍然可以在加入時限制刪除嗎?
//find total count to delete
$stmt = $db->prepare("
SELECT
COUNT(*)
FROM app_logs
INNER JOIN users
ON users.user_id = app_logs.user_id
INNER JOIN computers
ON computers.computer_id = users.computer_id AND computers.account_id != :account
WHERE app_logs.timestamp < :cutoff_time
");
$binding = array(
'account' => 2,
'cutoff_time' => strtotime('-3 months')
);
$stmt->execute($binding);
//get total results count from above
$found_count = $stmt->fetch(PDO::FETCH_COLUMN, 0);
echo $found_count; //ex. 15324
//delete rows
$stmt = $db->prepare("
DELETE
FROM app_logs
INNER JOIN users
ON users.user_id = spc_app_logs.user_id
INNER JOIN computers
ON computers.computer_id = users.computer_id AND computers.account_id != :account
WHERE app_logs.timestamp < :cutoff_time
LIMIT :limit
");
$binding = array(
'account' => 2,
'cutoff_time' => strtotime('-3 months'),
'limit' => 2000
);
while($found_count > 0)
{
$stmt->execute($binding);
$found_count = $found_count - $binding['limit'];
}