2015-02-05 1 views
1

이것이 내가 생각할 수있는 유일한 방법이며 제한에 대한 오류가 발생합니다. 결과 루프가 상당히 클 수 있으므로 while 루프 내에서 청크를 삭제하려고합니다.내부 조인과 한계가있는 mysql 삭제

첫 번째 계산서가 올바르게 작동합니다. 그것은 두 번째 delete 문이며 그렇지 않습니다. 조인 및/또는 제한 사용으로 인해 추측됩니다. 가입하는 동안 삭제를 어떻게 제한 할 수 있습니까?

//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 docs으로

또한 in this answer, LIMITDELETE + JOIN 함께 사용할 수 없습니다에서이 작업을 수행.

어떻게 든 삭제를 제한해야한다면 LIMIT 섹션을 에뮬레이션하는 DELETE 문에 대한 조건을 생성하면됩니다.

  • 그런 다음 한계를 모방 경계 IDS를 선택합니다 (10 및 200을 말할 수) 당신이에서 값을 삭제하려는 쿼리

    1. 를 적어 최소 및 최대 행 'IDS : 예를 들어, 당신은 다음 단계를 수행 할 수 ID 경계 각 위한
    2. 이어서, 수 (최대 50의 경계 IDS는 50, 100, 150, 200이 될 수 있도록), WHEREAND id <= ? 갖는 함께 DELETE 문을 조회하고, 대신에 ID 경계마다 넣어 ?.
    3. 그래서 당신은 그들 각각의 특정 범위 (10 ~ 50] (50, 100] 등이 ...

    희망이 도움이에서 ID를 삭제, 4 개 유사한 쿼리를 끝낸다.