如果和子句中没有数据,则选择错误

时间:2018-02-12 10:39:18

标签: mysql sql database laravel

我有一个获取表单详细信息的查询,如果已经分配给某个用户,则丢弃formid。

$formIds = DB::table('tbl_staff_user_details')
          ->select(DB::raw('GROUP_CONCAT(forms_assigned) as form_ids'))
          ->first();
$formIds = array_unique(explode(",", $formIds->form_ids));
if (Input::has('form_id'))
{
     $sql = 'SELECT * from tbl_forms where id IN('.Input::get('form_id').')';
}
else
{
     $lm_ids = Input::get('law_id');            
     $sql =  'SELECT *
              FROM tbl_forms
              WHERE lm_id IN('.$lm_ids.') AND id 
              NOT IN('.join(",",$formIds).')';
}
$data = DB::select($sql);

当我dd($formIds)时,我得到" "

并出现错误:

  

语法错误或访问冲突:1064   在第3行(SQL:SELECT * FROM tbl_forms WHERE lm_id IN(1,2,3,4,5)AND   id NOT IN())

如果$sql为空,则如何触发$formIds

3 个答案:

答案 0 :(得分:1)

您可以filter空值:

$formIds = array_unique(explode(",", $formIds->form_ids));

$formIds = array_filter($formIds, function($item){
        return !empty($item);
});
if (Input::has('form_id'))
{
    $sql = 'SELECT * from tbl_forms where id IN('.Input::get('form_id').')';
}
else
{
     $lm_ids = Input::get('law_id');      
     if(!empty($formIds)){      
        $sql =  'SELECT *
          FROM tbl_forms
          WHERE lm_id IN('.$lm_ids.') AND id 
          NOT IN('.join(",",$formIds).')';
     }else{
       $sql =  'SELECT *
          FROM tbl_forms
          WHERE lm_id IN('.$lm_ids.');
     }
}

答案 1 :(得分:0)

  

如果$ formIds为null,如何触发$ sql。

编辑2:

  

如果AND id NOT IN('.join(",",$formIds).')$sql

,我不希望$formIds条款成为null的一部分
...
if($formsIds) $formIds = array_unique(explode(",", $formIds->form_ids)); // Dont forget this line

if (Input::has('form_id'))
{
     $sql = 'SELECT * from tbl_forms where id IN('.Input::get('form_id').')';
}
else
{
   $lm_ids = Input::get('law_id');
   if(is_null($formIds) || empty($formIds)) {        
     $sql = 'SELECT * FROM tbl_forms WHERE lm_id IN('.$lm_ids.')';
   } else {
     $sql = 'SELECT * FROM tbl_forms WHERE lm_id IN('.$lm_ids.') AND id NOT IN('.join(",",$formIds).')';
   }

}
$data = DB::select($sql);

if($data) {
   //Handle data here
} else {
   //$data is empty
}

答案 2 :(得分:0)

在构建查询的行中,只有在有意义的情况下才添加NOT IN子句。

$sql = "SELECT *
          FROM tbl_forms
          WHERE lm_id IN('.$lm_ids.')";

if ($formIds != null) {
     $sql .= ' AND id NOT IN('.join(",",$formIds).')';
}