计算where子句上每个值的sql结果

时间:2012-07-09 07:37:30

标签: php mysql sql

我有一张这样的表:

| ID | NAME | CATEGORY |

我想计算一组给定类别的行,我有一个类别数组,我想知道每个类别有多少行,我做的是:

$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);
}

我也尝试了'select count(ID) from item where CATEGORY IN ('.implode(',',$cat).')'

但这给了我总数 有没有办法在没有循环的情况下获得每个类别的计数?用SQL。
我的SGBD是MySQL

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:2)

试试这个sql:

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

代码:

$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);