注:此种方法返回的为表中记录数而不是数据量。
以regal库为例:
$conn = mysql_connect('localhost','root','');
mysql_select_db('regal');
$sql="SELECT information_schema.TABLES.TABLE_NAME FROM information_schema.TABLES WHERE table_schema = 'regal'";
$res=mysql_query($sql);
while ($result = mysql_fetch_assoc($res)) {
$tables[]=$result['TABLE_NAME'];
};
echo "
表名 | 数据量 |
foreach ($tables as $k=>$v) {
$sql_count="select count(*) AS nums,'".$v."' from ".$tables[$k];
$res_count=mysql_query($sql_count);
if (!empty($res_count)) {
$result_count = mysql_fetch_assoc($res_count);
echo "
".$result_count[$v].''.$result_count['nums'].'';}
}
echo "
" ;执行结果:
请注意以下查询的执行结果
1. "select count(*) AS nums,'".$v."' from ".$tables[$k];
2. "select count(id) AS nums,'".$v."' from ".$tables[$k];
这两条查询记录返回的结果是不同的,count(*)是对行数目进行计数,而count(id)是对id不为空的行计数。
关于select count()的 执行效率:
1.任何情况下 select count(*) from xxx 是最优选择;
2.尽量减少select count(*) from xxx where col = ‘xxx’ 这种查询;
3.杜绝select count(col) from xxx where col = ‘xxx’ 的出现。(其中col非主键)