我从错误的表中挑选并优化了mysql查询

时间:2016-08-11 04:18:28

标签: php mysql

我试图通过连接一些表来编写sql查询并执行sql查询

原始查询

  /////////////My Sql Condition Start//////////////
    $cond="";
    if($brand){ $cond.=" and cc.id= ".$brand."";}
    if($Carmodel){ $cond.=" and cv.v_prod_id= ".$Carmodel."";}
    if($minprice!="" and $maxprice!=""){
    $cond.=" and (cv.v_price between ".$minprice." and ".$maxprice.")";
    }elseif($minprice){ $cond.=" and cv.v_price >= ".$minprice."";
    }elseif($maxprice){ $cond.=" and v_price <= ".$maxprice."";}

    if($reg_year){ $cond.=" and cv.registration_year =".$reg_year."";}

    if($reg_city){ $cond.=" and cv.registration_city ='".$reg_city."'";}

    if($kms_min!="" and $kms_max!=""){ $cond.=" and (cv.kms_run between ".$kms_min." and ".$kms_max.")";
    }elseif($kms_min){ $cond.=" and cv.kms_run >= ".$kms_min."";
    }elseif($kms_max){ $cond.=" and cv.kms_run <= ".$kms_max."";}

    if($location){ $cond.=" and cv.v_location='".$location."'";}
    /////////////My Sql Condition End//////////////

 $sql = "select * from #__usedcar_variants cv inner join 
    #__usedcar_products cp  inner join 
    #__usedcar_categories cc on  
    cc.id=cp.prod_cat_id and cp.id=cv.v_prod_id and 
    cv.state='1' where  1 $cond order by adddate desc";

以下是如何创建网址

    <a href="index.php?option=com_used&view=product&Itemid=1&
pid='.$row->v_prod_id.'&vid='.$row->id.'" target="_blank">Visit this Page</a>

网址中的问题是

`&vid='.$row->id.`

其中id取自表类别,而我希望从表格产品中挑选ID

如何确保从桌面产品中挑选ID 另外 - 是否有一种方法可以优化SQL查询 感谢

被修改

重写查询

    $sql = "select cc.id as prod_cat_id,
            cp.id as v_prod_id,
            cv.id as id
            from #__usedcar_variants
            inner join #__usedcar_products on 
#__usedcar_products cp = #__usedcar_categories cc
            where 1 $cond order by adddate desc ";

重写网址

 <a href="index.php?option=com_used&view=product&Itemid=1&
pid='.$row->v_prod_id.'&vid='.$row->usedcar_products.id.'" target="_blank">Visit this Page</a>

1 个答案:

答案 0 :(得分:0)

如果找到相同的密钥,则后面的ID将是最终的ID,因此请使用别名:

tab1.id name  |tab2.id name
1       Tom   |234     Tom
2       Mary  |2234    John

SELECT * FROM tab1 JOIN tab2 ON tab1.name = tab2.name

结果将是:

id  name
234 Tom

所以你需要使用别名,例如:

SELECT tab1.id AS id1, tab1.name, tab2.id AS id2
FROM tab1 JOIN tab2 ON tab1.name = tab2.name

将返回:

id1 name id2
1   Tom  234