MySQL Zend_Db:如何从表中获取行数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1930723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Zend_Db: How to get the number of rows from a table?
提问by Andrew
I want to find out how many rows are in a table. The database that I am using is a MySQL database. I already have a Db_Table class that I am using for calls like fetchAll()
. But I don't need any information from the table, just the row count. How can I get a count of all the rows in the table without calling fetchAll()
?
我想知道一个表中有多少行。我使用的数据库是 MySQL 数据库。我已经有一个 Db_Table 类,用于调用fetchAll()
. 但我不需要表中的任何信息,只需要行数。如何在不调用的情况下获取表中所有行的计数fetchAll()
?
回答by Decent Dabbler
$count = $db->fetchOne( 'SELECT COUNT(*) AS count FROM yourTable' );
回答by Derek Illchuk
Counting rows with fetchAll
considered harmful.
计算fetchAll
被认为有害的行。
Here's how to do it the Zend_Db_Select way:
以下是使用 Zend_Db_Select 的方法:
$habits_table = new Habits(); /* @var $habits_table Zend_Db_Table_Abstract */
$select = $habits_table->select();
$select->from($habits_table->info(Habits::NAME), 'count(*) as COUNT');
$result = $habits_table->fetchRow($select);
print_r($result['COUNT']);die;
回答by Tomá? Fejfar
Proper Zend-Way is to use Zend_Db_Select like this:
正确的 Zend-Way 是像这样使用 Zend_Db_Select:
$sql = $table->select()->columns(array('name', 'email', 'status'))->where('status = 1')->order('name');
$data = $table->fetchAll($sql);
$sql->reset('columns')->columns(new Zend_Db_Expr('COUNT(*)'));
$count = $table->getAdapter()->fetchOne($sql);
This is how it's done in Zend_Paginator. Other option is to add SQL_CALC_FOUND_ROWS
before your column list and then get the number of found rows with this query:
这就是 Zend_Paginator 中的做法。其他选项是SQL_CALC_FOUND_ROWS
在列列表之前添加,然后使用此查询获取找到的行数:
$count = $this->getAdapter()->fetchOne('SELECT FOUND_ROWS()');
回答by Peter Lang
You could do a
你可以做一个
SELECT COUNT(*)
FROM your_table
回答by Rob
$dbo->setFetchMode( Zend_Db::FETCH_OBJ );
$sql = 'SELECT COUNT(*) AS count FROM @table';
$res = $dbo->fetchAll( $sql );
// $res[0]->count contains the number of rows
回答by Roy Toledo
Add count capability to your Zend_DB Object To count all table rows
向 Zend_DB 对象添加计数功能以计算所有表行
public function count()
{
return (int) $this->_table->getAdapter()->fetchOne(
$this->_table->select()->from($this->_table, 'COUNT(id)')
);
}
回答by stagl
I'm kind of a minimalist:
我是一个极简主义者:
public function count()
{
$rows = $db->select()->from($db, 'count(*) as amt')->query()->fetchAll();
return($rows[0]['amt']);
}
Can be used generically on all tables.
可以在所有表上通用。