开发者

How can I Select the MAX of a Column using Zend_Db_Table?

开发者 https://www.devze.com 2023-02-18 15:14 出处:网络
开发者_开发技巧What is the easiest, simplest way to select the max of a column from a table using Zend_Db_Table?Basically, I just want to run this query in Zend:
开发者_开发技巧

What is the easiest, simplest way to select the max of a column from a table using Zend_Db_Table? Basically, I just want to run this query in Zend:

SELECT MAX(id) AS maxID FROM myTable;


You need to use Zend_Db_Expr to use mysql functions:

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


You can run direct sql, using $db->query(); yours would simply be:

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

but if you want the object notation, then you'd do something like this:

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


For those looking to just select the max id from their id column in Zend Framework 2 (maybe 3 as well), but getting this error...

While processing primary key data, a known key id was not found in the data array

...note that you'll need to alias MAX(id) as id.

Example inside a table extended from the TableGateway class:

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


Another way is like this :

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

If You do it like this , you can edit it later easier!!!


$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);
0

精彩评论

暂无评论...
验证码 换一张
取 消