具有许多where子句组合的MySql Query

时间:2014-07-08 08:03:47

标签: php mysql sql database

我必须选择在Excel中下载报告,用户将在其中输入“从日期”,“到日期”和“市场名称”。基于该数据将从数据库中获取。所有3个字段都不是必需的,因此如果用户输入任何值,则它将根据该值获取数据,否则将获取所有数据。对于3个字段,我必须编写8个where子句的组合,所以我的问题是如果有来自用户端的更多输入值,那么我必须编写where子句的许多组合,有时甚至超过20种组合。有没有简单有效的方法来做到这一点。

<?php

    if($date_from != NULL && $date_to != NULL  && $market != NULL){

      $whereCondition = "WHERE Date >= '$date_from' AND Date <= '$date_to' AND marketId = '$market' ";

    }elseif($date_from == NULL && $date_to == NULL && $market == NULL){

       $whereCondition = "WHERE 1";

    }elseif($date_from != NULL && $date_to == NULL  && $market != NULL){

        $whereCondition = "WHERE Date >= '$date_from' AND marketId = '$market' ";

    }elseif($date_from != NULL && $date_to == NULL  && $market == NULL){

         $whereCondition = "WHERE Date >= '$date_from' ";

    }elseif($date_from == NULL && $date_to != NULL  && $market != NULL){

        $whereCondition = "WHERE Date <= '$date_to' AND marketId = '$market' ";

    }elseif($date_from == NULL && $date_to != NULL  && $market == NULL){

        $whereCondition = "WHERE Date <= '$date_to'";

    }elseif($date_from == NULL && $date_to == NULL  && $market != NULL){

        $whereCondition = "WHERE marketId = '$market' ";

    }elseif($date_from != NULL && $date_to != NULL  && $market == NULL){

        $whereCondition = "WHERE Date >= '$date_from' AND Date <= '$date_to' ";
    }  


//finally my query will be below:
    //MYSQL QUERY
    $sql_data = "SELECT * FROM table_name $whereCondition ";

2 个答案:

答案 0 :(得分:0)

WHERE子句可以使用COALESCE函数表示,如果原始值为NULL,则提供备用值,如下所示:

 $whereCondition = "WHERE Date >= COALESCE('$date_from', Date) AND Date <= COALESCE('$date_to', Date) AND marketId = COALESCE('$market', marketId)";

因此,例如,如果'$date_from'为NULL,则它将采用当前行的Date列的值,使条件Date >= Date返回TRUE。

<强>参考

COALESCE function on MySQL Reference Manual

答案 1 :(得分:0)

构建数组并插入条件(如果需要): -

<?php

    $where_array = array();

    if($date_from != NULL)
    {
        $where_array[] = " Date >= '$date_from' ";
    }
    if($date_to != NULL)
    {
        $where_array[] = " Date <= '$date_to' ";
    }
    if($market != NULL)
    {
        $where_array[] = " marketId = '$market' ";
    }

    if (count($where_array) > 0)
    {
        $whereCondition = ' WHERE '.implode(' AND ', $where_array);
    }
    else
    {
        $whereCondition = '';
    }

//finally my query will be below:
    //MYSQL QUERY
    $sql_data = "SELECT * FROM table_name $whereCondition ";