日期:2014-05-17  浏览次数:20670 次

请教php大师---phpnewnew
我有2张数据表

a表
有 字段title

b表
也有字段title


a表中有1000条数据,b表中有10条数据

要求:

查询a表的title,若a.title 在 b.title中,则a.title存入 $array1中,如果sizeof($array1)>5 ,则不存。

若 若a.title 不在 b.title中,则 则a.title存入 $array2中,如果sizeof($array2)>5 ,则不存。

我的做法
PHP code
$sql="select title from a"
........
while($tpl2result=mysql_fetch_array($result_sql))
          {
              if(sizeof($array1)<5)
              {
               if($this->guolv($tpl2result['title']))
                 array_push($array1,$tpl2result);           
             }
             if(sizeof($array2)<5)
             {
             if(!$this->guolv($tpl2result['title']))
                 array_push($array2,$tpl2result);
             }
             if(sizeof($newtalk)==5&&sizeof($newvote)==5)
             {
                 break;    
                 exit;
             }
          }


questions:

 这种做法极大地浪费了资源,减慢速度,向大师取经。。


------解决方案--------------------
可以google一下sql语句的 join 操作
select * from a left join b on a.title = b.title
select * from a right join b on a.title = b.title

这样就不需要sql语句来对比两张表了

在数据库中,join的效率是很高的
------解决方案--------------------
就是嘛。你只要a.title表, LEFT JOIN 一次就够了,为NULL的就是不在b表咯。
长度sql len
或php判断下咯。
------解决方案--------------------
select title from a left join b on a.title=b.title limit 0,10
貌似这样是限制在10条内了
------解决方案--------------------
刚睡醒,大师就别叫了,这个就不扯了,你心知肚明,我也知道.

代码没有经过实战,仅仅做为思路,表必须做好索引,不过用title做索引我没有做过测试,我的Mysql 比php掌握得还少.

PHP code


$array1 = array();
$SQL = "SELECT a.title As atitle FROM a WHERE a.title in(SELECT b.title FROM b)";
$mysql->query($SQL);

$total = 0;
while ($result = $mysql->fetch_assoc()) {
    $array[] = $result['atitle'];
    if ($total > 5) {
        break;
    }
    $total++;

}
$array2 = array();
$SQL = "SELECT a.title As atitle FROM a WHERE a.title not in(SELECT b.title FROM b)";
$total = 0;
while ($result = $mysql->fetch_assoc()) {
    $array2[] = $result['atitle'];
    if ($total > 5) {
        break;
    }
    $total++;
}

------解决方案--------------------

探讨

人家又没问你们,干嘛多嘴呀?
何况还答错了

------解决方案--------------------
你就b LEFT JOIN a 就好了。以b为主。

探讨

引用:

select title from a left join b on a.title=b.title limit 0,10
貌似这样是限制在10条内了


如果前面995条都不在b里面,,从996---1000在b里面,,似乎不行了吧,,

碰到这种需求貌似没有妥善的解决方法,,只能按1楼的搞了,效率比我那个高