如何使用Zend_Db_Table选择列的MAX?

问题描述 投票:10回答:5

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

SELECT MAX(id) AS maxID FROM myTable;
php mysql zend-framework zend-db-table
5个回答
11
投票

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

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

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
投票

对于那些只想从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;

1
投票

另一种方式是这样的:

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

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


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);
© www.soinside.com 2019 - 2024. All rights reserved.