【问题标题】:There has got to be a more efficient way to do this必须有一种更有效的方法来做到这一点
【发布时间】:2013-03-08 22:14:56
【问题描述】:

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

最终,图像表将被缩减为(3,500 张未保存/未过滤的图像)+(“X”已保存)+(“X”未过滤)。 saves/filters/images 之间的链接是给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);

【问题讨论】:

  • 您没有像前几天在您的问题中建议的那样在查询中执行所有这些操作有什么原因吗?
  • 是的,我遇到了取消链接部分的问题
  • 我觉得在while循环部分执行所有这些查询对我来说非常糟糕......
  • 你能不能只做一个查询,返回所有需要删除的url,然后在删除下运行类似的查询,然后删除文件? IE。两个查询。
  • 不,我必须一次性从数据库中删除文件,然后从图像所在目录中读取文件名到数组中,查询images 表中的 URL 数组并取消链接目录中存在文件但数据库中不存在 url 的位置

标签: php mysql optimization unlink


【解决方案1】:

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

首先,将选择 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';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    相关资源
    最近更新 更多