准备好的PHP SQL语句在没有GROUP BY子句的情况下返回false

时间:2017-08-03 16:07:59

标签: php mysql sql

我有一份准备好的声明:

if ( $statement = $this->connection->prepare("SELECT question_type, count(*) AS `count` FROM (SELECT question.*, left(question_body, locate('between', question_body)-2) AS question_type FROM question) q WHERE (q.question_type = ? AND q.response_value_id = ?)") ) {
    $statement->bind_param("si", $question_type, $response_value_id);
    $statement->execute();
    return $statement->get_result()->fetch_assoc();
} else {
    var_dump($this->db->error);
}

以下是查询:

SELECT question_type, count(*) AS `count` FROM 
(SELECT question.*, left(question_body, locate('between', question_body) - 2) 
AS question_type FROM question) 
q WHERE q.question_type = 'Did you return home' AND q.response_value_id = 4 

问题: 由于某种原因,虽然我已经尝试在phpMyAdmin上运行查询并且它完美地工作,但是准备好的语句返回false。 如果我执行准备好的语句而没有警告错误,我会收到错误:bind_param() on boolean

如果我添加到查询的末尾:

GROUP BY q.question_type

然后一切正常。但是,这不是我想要的,因为它为计数而不是0返回null,而且我也不明白它如何在没有GROUP BY的情况下工作。

3 个答案:

答案 0 :(得分:0)

不使用group by的聚合函数的使用,并且不允许在最新版本的mysql(5.7)中使用 检查你是否正确版本,无论如何尝试使用集合中没有提到的列的agregated函数 例如:

  "SELECT question_type, count(*) AS `count` 
    FROM (
      SELECT question.*, left(question_body, locate('between', question_body)-2) AS question_type 
      FROM question ) q 
  WHERE q.question_type = ? AND q.response_value_id = ?
  GROUP BY question_type)"

  "SELECT min(question_type), count(*) AS `count` 
    FROM (
      SELECT question.*, left(question_body, locate('between', question_body)-2) AS question_type 
      FROM question ) q 
  WHERE (q.question_type = ? AND q.response_value_id = ?)"

答案 1 :(得分:0)

如果您想按question_type计算,则需要添加GROUP BY q.question_type。否则,在select语句中取count(*)之前取出question_type。试试这个:

SELECT count(*) AS `count` FROM 
(SELECT question.*, left(question_body, locate('between', question_body)-2) 
AS question_type FROM question) 
q WHERE q.question_type = 'Did you return home' AND q.response_value_id = 4 

答案 2 :(得分:0)

除了显示其他字段(在您的示例中为question_type)之外,每当使用聚合函数时,必须使用GROUP BY。

您可以在使用GROUP BY时计算的字段上使用ISNULL