我该如何优化这个mysql / php查询?

时间:2012-01-14 07:42:01

标签: php mysql database

我的页面显示图像,我想显示与当前图像相关的上一张和下一张图像。目前,我运行相同的查询3x并使用"where"修改=, >, <语句。

它有效,但我觉得必须有更好的方法来做到这一点。

图片ID不是1,2,3,4,5。并且可能是1,2,10,20,21等。但如果效率更高,我愿意改变它。

mysql_select_db("database", $conPro);
$currentid = mysql_real_escape_string($_GET['currentid']);
$query ="SELECT * FROM database WHERE id ='".$currentid."' LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);                               
if ($affected_rows==1)
    { 
        $row = mysql_fetch_array($result)or die ('error:' . mysql_error());     
        $current_id = $row['id'];
        $current_header = $row['title'];
        $current_description =$row['desc'];
        $current_image = "http://".$row['img'];
        $current_url = "http://".$row['id']."/".$db_title."/";
        $current_thumb = "http://".$row['cloud'];
}

mysql_select_db("database", $conPro);   
$query ="SELECT * FROM database WHERE id <'".$currentid."' ORDER BY id DESC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);                               
if ($affected_rows==1)
    { 
    $row = mysql_fetch_array($result)or die ('error:' . mysql_error()); 
        $previous_id = $row['id'];
        $previous_header = $row['title'];
        $previous_description =$row['desc'];
        $previous_image = "http://".$row['img'];
        $previous_url = "http://".$row['id']."/".$db_title."/";
        $previous_thumb = "http://".$row['cloud'];
    }else{
        $previous_none = "true"; //no rows found
    }

mysql_select_db("database", $conPro);   
$query ="SELECT * FROM database WHERE id >'".$currentid."' ORDER BY id ASC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);                               
if ($affected_rows==1)
    { 
    $row = mysql_fetch_array($result)or die ('error:' . mysql_error()); 
        $next_id = $row['id'];
        $next_header = $row['title'];
        $next_description =$row['desc'];
        $next_image = "http://".$row['img'];
        $next_url = "http://".$row['id']."/".$db_title."/";
        $next_thumb = "http://".$row['cloud'];
    }else{
        $next_none = "true"; //no rows found
        }
mysql_close($conPro);

感谢您的时间

2 个答案:

答案 0 :(得分:2)

您不必每次都select_db。一旦你选择了一个数据库,它就会一直处于选中状态,直到你选择其他东西为止。

你无法真正摆脱两个单独的查询来获取下一个/上一个图像,但你可以使用联合查询伪造它:

(SELECT 'next' AS position, ...
FROM yourtable
WHERE (id > $currentid)
ORDER BY id ASC
LIMIT 1)

UNION

(SELECT 'prev' AS position, ...
FROM yourtable
WHERE (id < $currentid)
ORDER BY id DESC
LIMIT 1)

这将返回两行,其中包含一个名为“position”的伪字段,可以让您轻松识别哪一行是“下一个”记录,哪一行是“前一个”记录。请注意,括号是必需的,以便“order by”子句适用于各个查询。如果没有,mysql将从union序列中的最后一个查询中获取order by子句,并将其应用于完整的union结果。

答案 1 :(得分:0)

您可以先获取“上一个”WHERE id <'".$currentid."' ORDER BY id DESC,然后查询两个“上方”SELECT * FROM database WHERE id >= '".$currentid."' ORDER BY id ASC,然后只需要两个查询而不是三个。

相关问题