MySQL加入:如何简化给定的查询?

时间:2014-05-21 11:01:17

标签: php mysql sql

$sql="SELECT advertiser_name from broker_blocked_advertisers where pline=".$pLine." AND bid=".$cNr;
 $result=mysqli_query($conn,$sql);
 if(mysqli_num_rows($result)>0){

    while($row=mysqli_fetch_array($result)){
    $s=trim($row['advertiser_name']);
    $sql2= "SELECT clientid from rv_clients where clientname='{$s}'"; 
    $result2=mysqli_query($dbc,$sql2);

        while($row2=mysqli_fetch_array($result2)){
        $sql3= "SELECT campaignid from rv_campaigns where               clientid=".$row2['clientid']; 
        $result3=mysqli_query($dbc,$sql3);

                while($row3=mysqli_fetch_array($result3)){
                $sql4= "SELECT bannerid from rv_banners where campaignid=".$row3['campaignid']; 
                $result4=mysqli_query($dbc,$sql4);

                    while($row4=mysqli_fetch_array($result4)){
                    $block_adr[]= $row4['bannerid'];
                     }
                 }
          }
    }
 }    

任何人都建议我在单个查询中简化上面的代码??? 我认为上面的代码实际上是一种错误的方法,请帮助如何缩短它。

代码描述:这里我从sql表中获取一个值,并使用该值我前进到另一个查询,依此类推。

提前致谢

5 个答案:

答案 0 :(得分:3)

修订查询和脚本: -

$sql = "SELECT d.bannerid 
        FROM  broker_blocked_advertisers a
        INNER JOIN rv_clients b ON a.advertiser_name = b.clientname
        INNER JOIN rv_campaigns c ON b.clientid = c.clientid
        INNER JOIN rv_banners d ON c.campaignid = d.ampaignid
        WHERE a.pline=".$pLine." AND a.bid=".$cNr;
$result=mysqli_query($dbc,$sql);

while($row=mysqli_fetch_array($result))
{
    $block_adr[]= $row['bannerid'];
}

答案 1 :(得分:1)

这是可怕的(n + 1)潜伏期死亡,是其四倍。

循环中的每次迭代都是另一次网络往返。那将会扼杀你的表现。

想想“加入”。将所有数据一次性返回并在客户端进行排序。

这是一个简化的例子:

select *
from campaign
join banner
on campaign.id = banner.campaign_id

可以节省广告系列的循环次数。

答案 2 :(得分:1)

一站式查询

$sql="SELECT 
bann.bannerid,camp.campaignid,c.clientid,b.advertiser_name as advname
from
broker_blocked_advertisers as b,
rv_clients as c,
rv_campaigns as camp,
rv_banners as bann 
where b.pline=".$pLine."
AND bid=".$cNr."
AND c.clientname=advname.advertisername
AND camp.clientid=c.clientid
AND bann.campaign_id=camp.campaig_id"

答案 3 :(得分:0)

你可以使用像我这样的单一查询:

SELECT bannerid from rv_banners where campaignid=
(
    SELECT campaignid from rv_campaigns where clientid=
    (
         SELECT clientid from rv_clients where clientname=
         (
                SELECT advertiser_name from broker_blocked_advertisers where pline=".$pLine."
                AND bid=".$cNr;
         )
    )
);

答案 4 :(得分:0)

SELECT "bannerId" FROM rv_banners A, rv_campaigns B, rv_clients C, broker_blocked_advertisers  D
WHERE A.campaignid = B.campaignid AND B.clientid = C.clientname AND C.clientname = D.advertisername AND D.pline = ".$pline." AND D.bid = ".$cNr;