带内部联接和限制的mysql删除

带内部联接和限制的mysql删除,mysql,delete-row,Mysql,Delete Row,这是我唯一能想到的方法,我得到了一个关于极限的错误。我试图在while循环中分块删除,因为结果总数可能相当大 第一个count语句工作正常。这是第二个delete语句,它不包含。我猜测是因为连接和/或使用限制。在加入时如何限制删除 //find total count to delete $stmt = $db->prepare(" SELECT COUNT(*) FROM app_logs INNER JOIN users ON u

这是我唯一能想到的方法,我得到了一个关于极限的错误。我试图在while循环中分块删除,因为结果总数可能相当大

第一个count语句工作正常。这是第二个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'];
}
//查找要删除的总计数
$stmt=$db->prepare(“
挑选
计数(*)
从应用程序日志
内部加入用户
ON users.user\u id=app\u logs.user\u id
内部连接计算机
在计算机上。计算机id=用户。计算机id和计算机。帐户id!=:帐户
其中app_logs.timestamp<:截止时间
");
$binding=数组(
“帐户”=>2,
“截止时间”=>strottime(“-3个月”)
);
$stmt->execute($binding);
//从上面获取总结果计数
$found_count=$stmt->fetch(PDO::fetch_列,0);
echo$found\u计数//例15324
//删除行
$stmt=$db->prepare(“
删除
从应用程序日志
内部加入用户
ON users.user\u id=spc\u应用程序\u日志.user\u id
内部连接计算机
在计算机上。计算机id=用户。计算机id和计算机。帐户id!=:帐户
其中app_logs.timestamp<:截止时间
极限:极限
");
$binding=数组(
“帐户”=>2,
“截止时间”=>strottime(“-3个月”),
“限制”=>2000
);
而($found\u count>0)
{
$stmt->execute($binding);
$found_count=$found_count-$binding['limit'];
}
同时,
限制
不能与
删除+加入一起使用

如果需要以某种方式限制删除,只需为
DELETE
语句创建条件,该语句将模拟
limit
部分。例如,您可以按照以下步骤操作:

  • 从要从中删除值的查询中获取最小和最大行ID(例如:10和200)
  • 然后选择模仿您的限制的边界ID(因此对于限制50,边界ID可以是50、100、150、200)
  • 然后,对于每个边界id,查询一个
    DELETE
    语句,其中
    WHERE
    具有
    和id