2015-02-05 82 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。