我有一张这样的表:
| 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
答案 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);