简体   繁体   中英

count sql results for each value on where clause

I have a table like this:

| ID | NAME | CATEGORY |

I want to count rows for a given set of categories, I have an array of categories, and I want to know how many rows for each category, what I did is:

$cats = array(2,4,5,1,8,44,47);
foreach($cats as $cat){
  $res = mysql_fetch_assoc(mysql_quer('select count(ID) from item where CATEGORY='.$cat);
}

I tried also 'select count(ID) from item where CATEGORY IN ('.implode(',',$cat).')'

But this gives me the total count.
Is there a way to get the count per category without looping? With SQL.
My SGBD is MySQL

select count(ID), category 
from item 
     where 
       CATEGORY IN ('.implode(',',$cat).') 
group by category

Try this sql:

SELECT count(ID) FROM item WHERE category IN (...) GROUP BY category

Code:

$cats = array(2,4,5,1,8,44,47);
$ret = mysql_query('SELECT category, count(ID) as count FROM item WHERE category IN ('.join(',', $cats).') GROUP BY category');
if (!$ret) {
  die(mysql_error());
}
$results = array();
while($row = mysql_fetch_assoc($ret)) {
  $results[$row['category']] = $row['count'];
}
var_dump($results);

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