必须有一种更有效的方法来做到这一点

时间:2012-10-18 15:57:59

标签: php mysql optimization unlink

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

最终,图像表将被裁剪为(3,500个未保存/未过滤的图像)+(“X”保存)+(“X”未过滤)。 save / filters / images之间的链接是赋予images表中记录的auto_incremented id。因此,save有一个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);

1 个答案:

答案 0 :(得分: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';