2015-02-05 147 views
1

這是我能想到做到這一點的唯一方法,並且我得到了關於限制的錯誤。我試圖在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']; 
} 

回答

-1

當在刪除查詢中有多個表時,您需要告訴DB從哪個表中刪除。您在第一行

DELETE app_logs 
FROM app_logs 
INNER JOIN users ON ... 
INNER JOIN computers ON ... 
0

由於mentioned in the docsin this answerLIMIT不能沿着DELETE + JOIN使用做到這一點。

如果您需要以某種方式限制刪除,只需創建DELETE語句的條件,即可模擬您的LIMIT部分。例如,你可以請按照下列步驟操作:

  1. 取最小值和最大值行IDS從要從刪除值查詢(可以說:10和200)
  2. 然後選擇接壤IDS模仿你的極限(因此對於限制50,接壤IDS可以是50,100,150,200)
  3. 然後,對於每個接壤ID,查詢DELETE語句與具有AND id <= ?WHERE,並把每一個的地方接壤ID?
  4. 所以,你最終與4個類似的查詢,他們每個人從一定範圍內(10-50],(50,100]等。

希望這有助於刪除IDS。