我们的 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/