如何使用Zend_Db_Table选择列的MAX?

时间:2011-03-21 16:55:04

标签: php mysql zend-framework zend-db-table

使用Zend_Db_Table从表中选择列的最大值的最简单最简单的方法是什么?基本上,我只想在Zend中运行此查询:

SELECT MAX(id) AS maxID FROM myTable;

5 个答案:

答案 0 :(得分:11)

您需要使用Zend_Db_Expr来使用mysql函数:

return $this->fetchAll(
            $this->select()
                ->from($this, array(new Zend_Db_Expr('max(id) as maxId')))
            )
    );

答案 1 :(得分:3)

您可以使用$db->query();直接运行sql,只需:

$db->query("SELECT MAX(id) AS maxID FROM myTable");

但是如果你想要对象符号,那么你会做这样的事情:

$db->select()->from("myTable", array(new Zend_Db_Expr("MAX(id) AS maxID")));

答案 2 :(得分:2)

对于那些希望从Zend Framework 2中的id列中选择最大id的人(也许还有3个),但是收到此错误......

  

处理主键数据时,在数据数组中找不到已知的键ID

...请注意,您需要将MAX(id)设为id

TableGateway类扩展的表中的示例:

$select = $this->sql->select();
$select->columns(['id' => new Expression('MAX(id)')]);
$maxId = $this->selectWith($select)->current()->id;
return (int) $maxId;

答案 3 :(得分:1)

另一种方式是这样的:

$select=new Zend_Db_Select($db);
$select->from(array($table),array('max($column)'));
$select->where('condition');
$answer=$db->fetchOne($select);

如果您这样做,可以稍后再编辑!!!

答案 4 :(得分:0)

$select = new Select();
$select->from('tablename');
$select->where(array('post_id', 1));
$select->columns(array('id' => new Expression('MAX(id)')));
$results = $this->getTableGateway()->selectWith($select);
相关问题