MySQL Select未根据给定条件进行选择

时间:2016-08-31 08:36:18

标签: mysql

我正在尝试运行SQL查询,但它没有向我显示确切的数据。 在我的搜索选项中,我有4个选项:按开始日期和结束日期搜索,按网站,按着陆页和品牌搜索。

当我按日期和网站搜索时,查询运行正常,但当我按着陆页和品牌搜索时,它会显示所有值。我希望用户可以选择按网站,登录页面或品牌进行搜索,或者用户可以按所有字段进行搜索,但需要选择日期。

这是我正在运行的查询:

$sql = "
    SELECT brand, cpa, sum(ftds), website, landingpage, ftddate
    FROM ftd
    WHERE ftddate BETWEEN CAST('$startdate' AS DATE)
    AND CAST('$enddate' AS DATE)
    AND (website='$website')
    OR (landingpage='$landingpage') 
    group by brand
";

1 个答案:

答案 0 :(得分:0)

试试这个

$sql ="SELECT `brand`, `cpa`, sum(`ftds`),`website`,`landingpage`,`ftddate` FROM ftd WHERE `ftddate` BETWEEN CAST('$startdate' AS DATE) AND CAST('$enddate' AS DATE) AND ((`website`='$website') OR (`landingpage`='$landingpage') OR (`brand`='$brand')) group by `brand`"; 

<强>更新:

        $concatenate='';

        $group_by_string ='  group by `brand`';
        ^^^^^^^^^^^^^^^^

        if(!empty($website))
        {
           $concatenate.=" AND `website`='$website'  ";

        }
        if(!empty($landingpage))
        {
           $concatenate.=" AND `landingpage`='$landingpage'  ";
        }
        if(!empty($brand))
        {
            $concatenate.=" AND `brand`='$brand'  ";
            $group_by_string ='  group by `landingpage`';
            ^^^^^^^^^^^^^^^^                

        }

        $sql ="SELECT `brand`, `cpa`, sum(`ftds`),`website`,`landingpage`,`ftddate` 
        FROM ftd 
        WHERE `ftddate` 
        BETWEEN CAST('$startdate' AS DATE) 
        AND CAST('$enddate' AS DATE) 
        $concatenate  $group_by_string ";
        ^^^^^^^^^^^

更新2
     当品牌不为空并且全部为空时,以下条件覆盖$ sql查询字符串。这个符合你的期望

        if(!empty($brand) && empty($website) && empty($landingpage))
       {
       $sql ="SELECT `brand`, `cpa`, `ftds`,`website`,`landingpage`,`ftddate` 
        FROM ftd 
        WHERE `ftddate` 
        BETWEEN CAST('$startdate' AS DATE) 
        AND CAST('$enddate' AS DATE) 
        $concatenate  $group_by_string";

        }