【问题标题】:Limit MYSQL query to 1 result stop failure of fetch_assoc()将 MYSQL 查询限制为 fetch_assoc() 的 1 个结果停止失败
【发布时间】:2015-03-29 00:21:13
【问题描述】:

如何将我的数据库查询限制为只有 1 个结果,以便 fetch_assoc() 不会失败。限制 1 似乎不起作用,我得到的错误和下面带有 sql 的 php 函数。

警告:mysqli::query(): (21000/1242): 子查询在 /class.php 的第 463 行返回多于 1 行

致命错误:在第 465 行的 /class.php 中的非对象上调用成员函数 fetch_assoc()

public function getLastTimeStampStatusChanged($column) {

    $sql = "select max(`timeStamp`) from `status` where `".$column."` !=(select `".$column."` from `status` where `timeStamp` = (select max(`timeStamp`) from `status` LIMIT 1))";

    while (!$query) {

        $query = $this->db->query($sql);

        while ($row = $query->fetch_assoc()) {

            $result[] = $row;

        }

    }

    return $result;


}

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    简短的回答是,您需要在 SELECT 列表中没有聚合的查询上使用 LIMIT 子句。最低限度的解决方法是移动结束括号...

    改变这个:

    ... from `status` LIMIT 1))
                             ^
    

    到这里:

    ... from `status`) LIMIT 1)
                     ^
    

    更长的答案是这可能不会返回您想要的结果,因为它只会返回一些行,而不是任何确定的行。

    【讨论】:

      【解决方案2】:

      应该是这样的

      public function getLastTimeStampStatusChanged($column) {
      
          $sql = "select max(`timeStamp`) from `status` where `".$column."` !=(select `".$column."` from `status` where `timeStamp` = (select max(`timeStamp`) from `status` ) LIMIT 1 )";
      
          while (!$query) {
      
              $query = $this->db->query($sql);
      
              while ($row = mysql_fetch_assoc($query)) {
      
                  $result[] = $row;
      
              }
      
          }
      
          return $result;
      
      
      }
      

      【讨论】:

        【解决方案3】:

        错误消息为您提供修复它所需的一切。简单的子查询返回不止一行。

        首先从子查询中删除LIMIT 1(您正在使用MAX,所以它只会返回一行)。然后将该限制添加到子查询中。

        select `".$column."` from `status` where `timeStamp` = (select max(`timeStamp`) from `status`) LIMIT 1
        

        您还应该删除while (!$query) 语句。这里没有任何意义。

        【讨论】:

          猜你喜欢
          • 2013-12-23
          • 2010-10-01
          • 2015-01-19
          • 2017-02-17
          • 1970-01-01
          • 2014-05-12
          • 1970-01-01
          • 1970-01-01
          • 2021-06-24
          相关资源
          最近更新 更多