将两个查询优化为一个并分离结果

时间:2015-04-20 14:09:01

标签: php mysql

如何优化此代码?是否可以成为一个查询?

此代码将我的广告信息提供给我的网站。同时将我的按摩放入数据库然后打电话给他们是否正确?

$result1 = mysql_query( "SELECT * FROM msg WHERE type='container'" , $link);

    while($end = mysql_fetch_assoc($result1)) {
        $msg=$end['msg'];
        $msg_class=$end['msg_class'];

 $msg_container[]='<div class="'.$msg_class.'">'.$msg.'</div>';
    }


$result2 = mysql_query( "SELECT * FROM msg WHERE type='leftbar'" , $link);

    while($end = mysql_fetch_assoc($result2)) {
        $msg=$end['msg'];
        $title=$end['title'];
        $msg_class=$end['msg_class'];

 $msg_leftbar[]='<div class="'.$msg_class.'"><h2>'.$title.'</h2><hr />'.$msg.'</div>';
    }

编辑: 如果在查询中有ORDER BY RAND()LIMIT 1,就像那样:

$result1 = mysql_query( "SELECT * FROM msg WHERE type='container' ORDER BY RAND() LIMIT 1" , $link);

和其他没有&#t; t:

$result2 = mysql_query( "SELECT * FROM msg WHERE type='leftbar'" , $link);

现在可以混合使用吗?

3 个答案:

答案 0 :(得分:4)

是的,你可以试试这个

$result = mysql_query( "SELECT msg, title, msg_class, type FROM msg WHERE type in ('container', 'leftbar' )" , $link);

while($end = mysql_fetch_assoc($result)) {

     $msg       =   $end['msg'];
     $msg_class =   $end['msg_class'];
     $title     =   $end['title'];

    if ($end['type'] == 'container') {
        $msg_container[]='<div class="'.$msg_class.'">'.$msg.'</div>';
    }

    if ($end['type'] == 'leftbar') {
        $msg_leftbar[]='<div class="'.$msg_class.'"><h2>'.$title.'</h2><hr />'.$msg.'</div>';
    }

}

答案 1 :(得分:1)

不确定。您可以使用一个查询和一个循环,并在该循环中具有检查当前行所属类型的条件。

$result = mysql_query( "SELECT * FROM msg WHERE type='container' OR type='leftbar'" , $link);

    while($end = mysql_fetch_assoc($result)) {
       $msg=$end['msg'];
       $msg_class=$end['msg_class'];
       $title = $end['title'];

       if($end['type'] == "container"){
          $msg_container[]='<div class="'.$msg_class.'">'.$msg.'</div>';
       } else {
          $msg_leftbar[]='<div class="'.$msg_class.'"><h2>'.$title.'</h2><hr />'.$msg.'</div>';
        }
    }

答案 2 :(得分:1)

你可以在一个sql中处理它,并在while块中决定它的类型

    $result1 = mysql_query( "(SELECT * FROM msg WHERE type='container' ORDER BY RAND() LIMIT 1) UNION 
    ( SELECT * FROM msg WHERE type = 'leftbar')" , $link);

                while($end = mysql_fetch_assoc($result1)) 
            {
            $msg = $end['msg'];
        $title = $end['title'];
        $msg_class = $end['msg_class'];
        $type = $end['type'];

        switch($type)
        {
            case 'container':
                $msg_container[]='<div class="'.$msg_class.'">'.$msg.'</div>';
            break;
            case 'leftbar':
                $msg_leftbar[]='<div class="'.$msg_class.'"><h2>'.$title.'</h2><hr />'.$msg.'</div>';
            break;
        }
    }