首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从我的循环中排除MySQL查询(限制不必要的查询)

如何从我的循环中排除MySQL查询(限制不必要的查询)
EN

Stack Overflow用户
提问于 2012-09-09 18:43:01
回答 2查看 141关注 0票数 1

我向MySQL请求数据,但它减慢了整个脚本的运行速度。然而,我不知道如何让它走出循环。我尝试将其转换为PHP数组,但老实说,经过一天的尝试,我失败了。

代码语言:javascript
运行
复制
<?php

$id = '1';

include_once 'include_once/connect.php';

for ($x = 1; $x <= 5; $x++) {
for ($y = 1; $y <= 5; $y++) {

    $xy = $x."x".$y;

    $pullMapInfo = "SELECT value FROM mapinfo WHERE id='".$id."' AND xy='".$xy."'";
    $pullMapInfo2 = mysql_query($pullMapInfo) or die('error here');

    if ($pullMapInfo3 = mysql_fetch_array($pullMapInfo2)) {
        #some code
    } else {
        #some code
    }
}
}

?>

如何让MySQL查询$pullMapInfo2跳出循环,缩短一次查询加载时间?

如果你想在你的本地主机上启动脚本,你可以c&p全部:-)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-09-09 18:57:20

使用MySQL IN子句

代码语言:javascript
运行
复制
<?php

$id = '1';

include_once 'include_once/connect.php';

// first we create an array with all xy
$array = array();
for ($x = 1; $x <= 5; $x++) {
    for ($y = 1; $y <= 5; $y++) {
        $xy = $x."x".$y;
        $array[] = $xy;
    }
}

$in = "'" . implode("', '", $array) . "'";
$pullMapInfo = "SELECT xy, value FROM mapinfo WHERE id='".$id."' AND xy IN ({$in})";
$pullMapInfo2 = mysql_query($pullMapInfo) or die('error here');

// we create an associative array xy => value
$result = array();
while (($pullMapInfo3 = mysql_fetch_assoc($pullMapInfo2)) !== false) {
    $result[ $pullMapInfo3['xy'] ] = $pullMapInfo3['value'];
}


// we make a loop to display expected output
foreach ($array as $xy)
{
    if (array_key_exists($xy, $result)) {
        echo '<div class="castle_array" style="background-image: url(tiles/'.$result[$xy].'.BMP)" id="'.$xy.'">'. $result[$xy] .'</div>';
    } else {
        echo '<div class="castle_array" id="'.$xy.'"></div>';
    }
    echo '<div class="clear_both"></div>';
}

?>
票数 0
EN

Stack Overflow用户

发布于 2012-09-09 19:02:01

我不确定您的表中有什么,但考虑到您基本上遍历了表中的几乎所有内容,我建议您对给定的Id执行一次查询,然后从较大的数据集中整理出所需的内容。

特别是如果您总是从本质上为每个id拉回完整的数据集,那么甚至没有理由为IN查询而烦恼,只需将其拉回到单个PHP数组中,然后根据需要遍历该数组。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12338397

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档