PHP MySQL-1 查询计数并显示不同 "status"上的记录

标签 php mysql count

我有一个表,其中的记录具有不同的“状态”。到目前为止,我使用单独的查询来根据“状态”调用这些记录的数量。我认为(希望)有更好的方法(更快)来做到这一点。有什么想法吗?

我的 SQL:

$res1 = $mysqli->query("SELECT status FROM test WHERE status='1'") 
$num_1 = mysqli_num_rows($res1);

$res2 = $mysqli->query("SELECT status FROM test WHERE status='2'") 
$num_2 = mysqli_num_rows($res2);

$res3 = $mysqli->query("SELECT status FROM test WHERE status='3'") 
$num_3 = mysqli_num_rows($res3);

我的 PHP

echo $num_1;
echo $num_2;
echo $num_3;

最佳答案

如果您只需要获取每个状态的计数,您可以使用group by子句在一个查询中执行此操作。

select `status`,count(`status`) as 'count' from `test` group by `status`;

这将返回如下记录集:

+--------+-------+
| status | count |
+--------+-------+
|      1 |    10 |
|      2 |     8 |
|      3 |    12 |
|      4 |     8 |
|      5 |     7 |
|      6 |     3 |
|      7 |     9 |
+--------+-------+

因此,在 PHP 中运行查询后,您可以执行以下操作:

while( $rs=$result->fetch_object() ) echo $rs->status.'='.$rs->count;



$dbhost = 'localhost';
$dbuser = 'xxx'; 
$dbpwd  = 'xxx'; 
$dbname = 'xxx';
$db  =  new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

$sql="select `status`, count(`status`) as 'count' from `test` group by `status`;";
$result=$db->query( $sql );

while( $rs=$result->fetch_object() ) {
    echo '<div>Status: ' . $rs->status.', Total: ' . $rs->count . '</div>';
}

$db->close();
$db=null;

关于PHP MySQL-1 查询计数并显示不同 "status"上的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39423101/

相关文章:

java - 如何设置 SMS 服务器?

php - 在 laravel 5 中,如何从外部类访问 Command 类方法?

mysql - 通过函数进行内连接

mysql - 从 Servlet 在 JSP 中显示数据表

php - 我的 JOIN + GROUP BY ... HAVING COUNT 查询是否正确?

jquery 计算带有属性的元素

php - 填充和类 col-md 不起作用

php - CakePHP 3.0 - $this->Model->get($id) 引发 MySQL 错误

mysql - 简单的 MYSQL 计数、分组依据,无法使用 Pentaho Report Designer CE 工作

php - 滑动 jquery 表单不会转换超过一次