PHP输出多个SQL查询结果数

时间:2014-12-24 18:48:27

标签: php mysql count

我有五个不同的SQL查询,我想返回列表中返回的行数。基本上我有一个MySQL数据库,想要显示一些关于我们有多少记录以及有多少记录添加了信息的统计数据。查询的示例是......

SELECT * FROM `ibf_ccs_custom_database_1` 
SELECT * FROM `ibf_ccs_custom_database_2` 
SELECT * FROM `ibf_ccs_custom_database_3` 
SELECT * FROM `ibf_ccs_custom_database_1` WHERE `field_30` <> ''
SELECT * FROM `ibf_ccs_custom_database_2` WHERE `field_60` <> ''

哪个应该返回以下输出

Total Records Database 1: 12,548
Total Records Database 2: 9,835
Total Records Database 3: 5,916
Filled Out Records in Database 1: 567
Filled Out Records in Database 2: 681

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

我只是用key =&gt;构建一个数组;行数的值对。像这样:

$db_queries = array();

$query = "SELECT * FROM ibf_ccs_custom_database_1";
$res = $mysqli->query($query);
$db_queries['q1'] = $res->num_rows;

$query = "SELECT * FROM ibf_ccs_custom_database_2";
$res = $mysqli->query($query);
$db_queries['q2'] = $res->num_rows;

$query = "SELECT * FROM ibf_ccs_custom_database_3";
$res = $mysqli->query($query);
$db_queries['q3'] = $res->num_rows;

$query = "SELECT * FROM ibf_ccs_custom_database_1 WHERE field_30 <> ''";
$res = $mysqli->query($query);
$db_queries['q4'] = $res->num_rows;

$query = "SELECT * FROM ibf_ccs_custom_database_2 WHERE field_60 <> ''";
$res = $mysqli->query($query);
$db_queries['q5'] = $res->num_rows;

foreach($db_queries as $k => $v){
    echo $k, " contains ", $v, " rows.";
}

答案 1 :(得分:0)

让数据库准备一个只包含行数的结果,而不是准备一万多行的完整集合,会更加高效

例如,让数据库返回结果,如问题所示:

 SELECT CONCAT('Total Records Database 1: ',FORMAT(COUNT(1),0) AS txt 
   FROM `ibf_ccs_custom_database_1` 
  UNION ALL
 SELECT CONCAT('Total Records Database 2: ',FORMAT(COUNT(1),0) 
   FROM `ibf_ccs_custom_database_2`
  UNION ALL
 SELECT CONCAT('Total Records Database 3: ',FORMAT(COUNT(1),0)
   FROM `ibf_ccs_custom_database_3`
  UNION ALL
 SELECT CONCAT('Filled Out Records in Database 1: ',FORMAT(COUNT(1),0)
   FROM `ibf_ccs_custom_database_1` WHERE `field_30` <> ''
  UNION ALL
 SELECT CONCAT('Filled Out Records in Database 1: ',FORMAT(COUNT(1),0)
   FROM `ibf_ccs_custom_database_2` WHERE `field_60` <> ''

如果您想在应用程序层中处理标签和格式,您只需将计数返回到一行:

 SELECT t1.cnt  AS t1_cnt
      , t2.cnt  AS t2_cnt
      , t3.cnt  AS t3_cnt
      , f1.cnt  AS f1_cnt
      , f2.cnt  AS f2_cnt
   FROM ( SELECT COUNT(1) AS cnt FROM `ibf_ccs_custom_database_1` ) t1
   JOIN ( SELECT COUNT(1) AS cnt FROM `ibf_ccs_custom_database_2` ) t2
   JOIN ( SELECT COUNT(1) AS cnt FROM `ibf_ccs_custom_database_3` ) t3
   JOIN ( SELECT COUNT(1) AS cnt FROM `ibf_ccs_custom_database_1` WHERE `field_30` <> '' ) f1
   JOIN ( SELECT COUNT(1) AS cnt FROM `ibf_ccs_custom_database_1` WHERE `field_60` <> '' ) f2