有什么办法可以最小化这个mysql查询?

时间:2010-10-08 00:51:55

标签: php mysql

我正在开发一个有八个广告盒的应用程序,有位置的广告数据存储在数据库中。

广告模块首先工作,它将检查数据库中是否存在特定位置(即1到8),如果找到或未找到它将相应地返回布尔值。

因为这个原因我正在使用这样的用户定义函数。

 function dbgetvar($query) {
             $res = mysql_query($query);
         if( !$res) {
             trigger_error("dbget: ". mysql_error(). " in " .$query);
             return false;
             }
             if( mysql_num_rows($res) == '0' ) {
             return false;
             }
             $row = mysql_fetch_array($res);
             if(!$row) return "";
             return $row;
             }

因为我必须进行八次查询,所以我这样做。

$adbox1 = dbgetvar("SELECT advertisements.id as 1_id, advertisements.pic_brief as 1_brief  FROM advertisements WHERE pos = '1'");
$adbox2 = dbgetvar("SELECT advertisements.id as 2_id, advertisements.pic_brief as 2_brief  FROM advertisements WHERE pos = '2'");
$adbox3 = dbgetvar("SELECT advertisements.id as 3_id, advertisements.pic_brief as 3_brief  FROM advertisements WHERE pos = '3'");
$adbox4 = dbgetvar("SELECT advertisements.id as 4_id, advertisements.pic_brief as 4_brief  FROM advertisements WHERE pos = '4'");
$adbox5 = dbgetvar("SELECT advertisements.id as 5_id, advertisements.pic_brief as 5_brief  FROM advertisements WHERE pos = '5'");
$adbox6 = dbgetvar("SELECT advertisements.id as 6_id, advertisements.pic_brief as 6_brief  FROM advertisements WHERE pos = '6'");
$adbox7 = dbgetvar("SELECT advertisements.id as 7_id, advertisements.pic_brief as 7_brief  FROM advertisements WHERE pos = '7'");
$adbox8 = dbgetvar("SELECT advertisements.id as 8_id, advertisements.pic_brief as 8_brief  FROM advertisements WHERE pos = '8'");

然后我获取这样的数据。

if($adbox1){
    echo "I am found";
}
if(!$adbox1){
    echo "I am not found";
}

虽然它工作正常,但它很混乱,并且堆积了大量的查询。如果可能的话,我想清理并尽量减少它。

你有什么看法?

2 个答案:

答案 0 :(得分:5)

这应该做你想要的:

$query = "SELECT id, pic_brief FROM advertisements WHERE pos BETWEEN 1 AND 8";
$res = mysql_query($query);
$adbox = array_fill(1, 8, null);
while ($row = mysql_fetch_array($res)) {
    $adbox[$row['id'] = $row;
}

您可以$adbox[1]['id'] / $adbox[1]['pic_brief']等方式访问数据。

编辑:我已更新代码以避免留下空的adbox ID。

答案 1 :(得分:3)

往返数据库的效率低于PHP中的循环。所以我的建议是将它最小化为一个查询(假设pos是一个整数),类似于:

SELECT id, pic_brief, pos FROM advertisements WHERE pos BETWEEN 1 AND 8;

然后像这样循环以构建一个数组:

$adbox = array();
while ($row = mysql_fetch_array($res)) {
  $adbox[$row['pos']] = $row
}

通过查找pos作为数组键来进行布尔测试:

if ($adbox[1]) {
  // has ad 1
}
else {
  // no ad 1
}

如果您愿意,可以将其分解为一个功能。但这是我对最小化的考虑。另一个好处是,您可以访问$adbox

中的广告数据