0

我有一张这样的桌子:

| 身份证 | 姓名 | 类别 |

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

$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

4

2 回答 2

5
select count(ID), category 
from item 
     where 
       CATEGORY IN ('.implode(',',$cat).') 
group by category
于 2012-07-09T07:39:15.343 回答
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);
于 2012-07-09T07:39:37.443 回答