Empty IN clause parameter list in MySQL

后端 未结 9 1026
攒了一身酷
攒了一身酷 2020-11-30 08:45

What happens when you do a SQL query where the IN clause is empty?

For example:

SELECT user WHERE id IN ();

Will MySQL

9条回答
  •  既然无缘
    2020-11-30 08:56

    If you use AUTO_INCREMENT for id (1,2,3, ..) and if array is empty, you can add one item [0]. So it will be

    if (empty($arr)) {
       $arr[] = 0;
    }
    
    SELECT user WHERE id IN (0);
    

    And there will be no mysql parse error. This case is very usefull in subqueries - when your main query is not dependent on subquery results.


    Better way - don't call the query if array is empty.

    $data = null;
    if (!empty($arr)) {
        $data = ... call query
    }
    

提交回复
热议问题