php - MySQL 用 Group By 计算项目数

标签 php mysql

我们的 MySQL 数据库中有这两个字段: in_model , in_color

我们正在尝试计算模型(in_model 字段)的总数,该模型在 PHP 中具有相同的颜色(in_color 字段),以 MySQL 作为后端数据库。我们尝试将 count() 函数与 group by 一起使用。但似乎我们没有达到预期的结果

这是我们的 MySQL 数据库:

$query = "SELECT in_model, COUNT(in_color) FROM in_newunit GROUP BY in_color,in_model";         
$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)) {  
    echo "There are ". $row['COUNT(in_color)'] ."  
         ". $row['in_model'] ."  items.";   
    echo "<br />";  
}

这是我们收到的输出

There are 1 C2I items. 
There are 2 try items. 
There are 2 try items. 
There are 4 C2I items.

这就是我们正在努力实现的目标

我们试图让颜色出现在 echo 中

There are 1 C2I Black items. 
There are 2 try White items. 
There are 2 try Black items. 
There are 4 C2I White items.

最佳答案

我认为这已经够直接了。试试这个。

$query = "SELECT in_model, in_color, count(*) AS counter FROM in_newunit GROUP BY in_model, in_color";         
$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)) {  
    echo "There are ". $row['counter'] ." ". $row['in_model'] ." ".$row['in_color']." items.";   
    echo "<br />";  
}

关于php - MySQL 用 Group By 计算项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19287806/

相关文章:

php - 当事件被触发时,我需要在 x 时间后检查某些内容?

php - Silex 路由 .htaccess webroot

php - jqueryForm 和空上传

mysql - SQL 从一个表复制到另一个表的适当字段

mysql - show profiles 不显示查询

php - 如何将数据提交到 php 页面而不立即转到该页面?

php - 如何使用事务查询 mysql 在 PHP 中将其保留在几个页面上?

mysql - 使用带单引号的值从数据库检索结果

php - 在Mysql中调用存储过程

mysql - 从大表中删除一列