当搜索参数值为null或为空时选择所有行[mysql]

时间:2018-03-07 06:10:53

标签: php mysql sql

我正在尝试使用多个搜索选项,用户可以选择多个选项来过滤记录。

当用户不选择过滤选项时,默认情况下应返回所有记录。

这是我的SQL查询:

$query = 
    sprintf("SELECT * FROM users_leave_request 
        where leave_from >= '$leave_from' 
        AND leave_to <= '$leave_to' 
        AND leave_status = '$leave_stat' 
        AND user_id = '$emp_id'");

    $result=$this->db->exec($query);

我打算做的是:

  1. 假设$leave_stat参数为空,则应返回所有leave_stat值的记录。
  2. 同样,如果$emp_id为空,则应返回所有用户的记录。
  3. 这有点像禁用*extra AND* where参数为空时的条件。

    我可以使用单个查询执行此操作,还是必须使用单独的查询? 很感谢任何形式的帮助。感谢。

2 个答案:

答案 0 :(得分:4)

您可以在查询之前检查过滤条件,例如

$whrcondn="";

$whrcondn.=($leave_from)?" and leave_from > = '$leave_from'":"";

$whrcondn.=($leave_to)?" and leave_to < = '$leave_to'":"";

$whrcondn.=($leave_status)?" and leave_status  = '$leave_stat'":"";

$whrcondn.=($emp_id)?" and user_id ='$emp_id'":"";

$query =  sprintf("select * from users_leave_request where 1=1 $whrcondn");

答案 1 :(得分:1)

看看这个简单的方法 添加此条件

(clojure.repl/doc partition-by) 
-------------------------
clojure.core/partition-by
([f] [f coll])
  Applies f to each value in coll, splitting it each time f returns a
   new value.  Returns a lazy seq of partitions.  Returns a stateful
   transducer when no collection is provided.

然后将leave_status和user_id改为$ x和$ y,如下所示:

if(!empty($leave_stat))
 {$x='leave_status';}
else
 {$x='leave_status!';}

if(!empty($leave_stat))
 {$y='user_id';}
else
 {$y='user_id!';}

祝你好运

相关问题