我想在这个条件下有一个WHERE?

时间:2014-03-11 05:43:32

标签: php mysql

我的MySQL中有这个问题,我有3个组合框,我想得到它们的值,所以我可以为它们创建一个过滤器。我希望这些代码有1 where,所以任何人都可以帮助我。 TIA

if($this->input->get('name')) 
            $name = $this->input->get('name');
        else   
            $name =  "";
        $namecondition = "";
            if(strlen($name) > 0)
                $namecondition .= "WHERE E.`nameid` = '$name'";

        if($this->input->get('age')) 
            $age = $this->input->get('age');
        else   
            $age =  "";
        $namecondition2 = "";
            if(strlen($age) > 0)
                $namecondition2 .= "WHERE E.`ageid` = '$name'";

        if($this->input->get('year')) 
            $year = $this->input->get('year');
        else   
            $year =  "";
        $namecondition = "";
            if(strlen($year) > 0)
                $namecondition3 .= "WHERE E.`yearid` = '$name'";            

        $sSQL = "SELECT *,COALESCE(E.`id`,0) AS 'eid'
                 FROM employee AS E
                 LEFT JOIN name AS B ON E.nameid = B.id
                 LEFT JOIN age AS C ON E.ageid = C.id
                 LEFT JOIN year AS J ON E.yearid = J.id
                 $namecondition
                 ORDER BY E.lastName ASC"; 

2 个答案:

答案 0 :(得分:0)

要连接这些WHERE,每次都需要AND而不是WHERE。并且只使用一个$namecondition变量来构建where字符串(无$namecondition2$namecondition3)。

所以你可以做这样的事情。默认情况下从虚拟开始:

$namecondition = "WHERE 1 ";

每个连接使用AND:

$namecondition .= " AND E.`nameid` = '$name'";

等...

这将创建:WHERE 1 AND first_condition AND second_condition...

答案 1 :(得分:0)

以下是您使用where 1=1的解决方案,并附加以AND开头的另一个字符串...

if($this->input->get('name')) 
        $name = $this->input->get('name');
    else   
        $name =  "";
    $namecondition = "";
        if(strlen($name) > 0)
            $namecondition .= " AND E.`nameid` = '$name'";

    if($this->input->get('age')) 
        $age = $this->input->get('age');
    else   
        $age =  "";
    $namecondition2 = "";
        if(strlen($age) > 0)
            $namecondition2 .= " AND E.`ageid` = '$name'";

    if($this->input->get('year')) 
        $year = $this->input->get('year');
    else   
        $year =  "";
    $namecondition = "";
        if(strlen($year) > 0)
            $namecondition3 .= " AND E.`yearid` = '$name'";            

    $sSQL = "SELECT *,COALESCE(E.`id`,0) AS 'eid'
             FROM employee AS E
             LEFT JOIN name AS B ON E.nameid = B.id
             LEFT JOIN age AS C ON E.ageid = C.id
             LEFT JOIN year AS J ON E.yearid = J.id
             where 1 = 1 
             $namecondition
             ORDER BY E.lastName ASC";