2

基本上我正在尝试将图像表修剪为 3,500 行未保存或未过滤的图像。未保存和未过滤指的是数据库中的其他表。用户可以保存图像以及将图像标记为安全工作等...我想将所有图像保留在保存表和过滤器表中。

最终,图像表将被修剪为(3,500 张未保存/未过滤的图像)+(“X”已保存)+(“X”未过滤)。保存/过滤器/图像之间的链接是赋予images表中记录的 auto_incremented id。所以 saves 有一个 image_id 字段来获取images表中记录的键。与过滤器表相同

//connect to database
$connect = xxxxxxxxxxx;


//GET ALL IMAGES FROM `images` Table - NEWEST FIRST (`id` is auto_increment)
$sql = mysql_query("SELECT * FROM `images` ORDER BY `id` DESC") or die(mysql_error());
$x = 0;
while($row = mysql_fetch_array($sql)){
    //GET CURRENT IMAGES ID AND URL
    $id = $row['id'];
    $file = $row['url'];

    //SEE IF IMAGE IS IN THE saves Table
    $saves = mysql_query("SELECT `id` FROM `saves` WHERE `img_id` = '".$id."'") or die(mysql_error());
    if(mysql_num_rows($saves) == 0){$saved = FALSE;}
    else {$saved = TRUE;}

    //SEE IF IMAGE IS IN THE filters Table
    $filter = mysql_query("SELECT `id` FROM `filter` WHERE `img_id` = '".$id."'") or die(mysql_error());
    if(mysql_num_rows($filter) == 0){$filtered = FALSE;}
    else {$filtered = TRUE;}

    //If the image has not been saved or filtered then put it in a que for deletion
    if(!$saved || !$filtered){
        $IdQue[$x] = $id;
        $FileQue[$x] = $file;
        $x++;
    }//END if   
}//END while

//Process the delete que: Delete node from database, delete file on server. Keep 3,500 of the newest images.
for($i=3500; $i<$x; $i++){
    mysql_query("DELETE FROM `images` WHERE id='".$IdQue[$i]."' LIMIT 1") or die("line 33".mysql_error());

    if(file_exists($FileQue[$i])){
        unlink($FileQue[$i]) or die("file Not deleted");
    }//END if
}//END for
echo ($i-3500)." files deleted<br/>";

//terminate connection
mysql_close($connect);
4

1 回答 1

0

这应该让你去某个地方,但不是完整的代码:

首先,将选择 id 减少到 2 个查询:

$missing_from_filters = SELECT id FROM images WHERE img_id NOT IN (SELECT img_id FROM filter)
$missing_from_saves = SELECT id FROM images WHERE img_id NOT IN (SELECT img_id FROM saves)

然后,获取两个数组中的 id

$to_delete = array_intersect($missing_from_filters,$missing_from_saves);

运行一个查询以将它们全部删除

$remove_query = 'DELETE FROM images WHERE img_id IN ( '.implode(',',$to_delete).') LIMIT 3500';
于 2013-03-08T14:05:25.610 回答