PHP中SQL_CALC_FOUND_ROWS与FOUND_ROWS()和count()

MySQL 4.1中新增了FOUND_ROWS()函数,关于这个函数的说明如下:

For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause

A SELECT statement may include a LIMIT clause to restrict the number of rows the server returns to the client. In some cases, it is desirable to know how many rows the statement would have returned without the LIMIT, but without running the statement again. To obtain this row count, include a SQL_CALC_FOUND_ROWS option in the SELECT statement, and then invoke FOUND_ROWS() afterward:

例如需要取出一张表的前10行,同时又需要取出符合条件的总数。这在某些翻页操作中很常见

SELECT SQL_CALC_FOUND_ROWS * FROM your_table_name

WHERE id > 33 LIMIT 10;

在上一查询之后,你只需要用FOUND_ROWS()就能获得查询总数,这个数目是抛掉了LIMIT之后的结果数:

SELECT FOUND_ROWS();

其中第一个sql里面的SQL_CALC_FOUND_ROWS不可省略,它表示需要取得结果数,也是后面使用FOUND_ROWS()函数的铺垫。

注意:FOUND_ROWS()返回的结果是临时的。如果程序往后会用到这个数字,必须提前它保存在一个变量中待用。

FOUND_ROWS()与count()的区别:

1、当SQL限制条件太多时, count()的执行效率不是很高,最好使用FOUND_ROWS()
2、当SQL查询语句没有where等条件限制时,使用count()函数的执行效率较高。

PHP的模型(Model)层:文件mod_demo.php

<?php
!defined('PATH_ADMIN') && exit('Forbidden');
class mod_demo
{
		public static function testgetresults($start = 0, $perpage = PAGE_ROWS)
		{
			if($start > -1 && $perpage >0)
			{
				$condition = "/* WHERE level = '2' OR level ='1' */ORDER BY user_id ASC";
			}
			$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM pm_admin_user $condition";
			$query = pm_db::query($sql);
			$arrdata = array();
			while($rowdata = pm_db::fetch_one($query))
			{
				$rowdata['add_time'] = date('Y-m-d',$rowdata['add_time']);
				$arrdata[] = $rowdata;
				
			}
			$arrout = array();
			if($arrdata)
			{
				$arrout['data'] = $arrdata;
				$arrout['count'] = pm_db::result_first("SELECT FOUND_ROWS() AS rowscount");
				return $arrout;
			}
			else
			{
				return null;
			}
		}
}
?>

控制(Controller)层文件pmc_demo.php

class pmc_demo
{
	public $_GP;
	function __construct()
	{
		$this->_GP = array_merge($_GET,$_POST);
		pm_tpl::assign('lang',$this->lang());
	}
	public function mytestdata()
	{

		$start = (isset($_GET['start']))? (int)$_GET['start'] : 0;
		//$start = (empty($_GET['start'])) ? 0 : (int)$_GET['start'];
		$datalist = mod_demo::testgetresults($start, PAGE_ROWS);
		if($datalist)
		{
			pm_tpl::assign('datalist',$datalist['data']);
			pm_tpl::assign('page_url',"?c=demo&a=mytestdata");
			pm_tpl::assign('pages',mod_pager::get_page_number_list($datalist['count'], $start, PAGE_ROWS));
		}
		pm_tpl::assign('ur_here','测试页面');
		pm_tpl::assign('keyword','@XXX.com');
		pm_tpl::display("demo_mytestdata");
	}
}

视图View层代码略。

你可能感兴趣的:(FOUND_ROWS)