简体   繁体   English

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

[英]count sql results for each value on where clause

I have a table like this: 我有一张这样的桌子:

| | ID | ID | NAME | 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).')' 我也尝试了'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. 用SQL。
My SGBD is MySQL 我的SGBD是MySQL

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

Try this sql: 试试这个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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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