简体   繁体   中英

MySQL Count number of Items with Group By

We have these two fields in our MySQL database: in_model , in_color

And we are trying to count the total of model (in_model field), which has the same color (in_color field) in PHP with MySQL as backend database. We tried using the count() function, together with the group by . But it would seem we don't have achieve a desired result

This is our MySQL database:

$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 />";  
}

This is the output we are receiving

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

This is what we are trying to achieve

We are trying to have the color appear in the 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.

I think this is straight enough. Try this.

$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 />";  
}

The query is actually the other way around:

SELECT in_color, count(*) FROM in_newunit
GROUP BY in_color

And you have actually said it yourself:

we are trying to count the total of model (in_model field), which has the same color (in_color field)

"count the total of model" > count(*)

"which has the same color" > for every color the previous count, which is a group by in_color

Also note that if you do count(in_model) you won't be counting values with in_model as null . If you do count(*) you will be counting the null values too. Up to you.

Update

So you want the amount of elements there are by (model, color) pair. Then this is the query:

SELECT in_model, in_color, count(*) FROM in_newunit
GROUP BY in_model, in_color

Eg:

model1 | black | 2
model1 | white | 1
model2 | black | 5
model3 | white | 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM