我的表格categories
有:id, name, subcategory_id, parent_id
。另一个表格classifieds
包含:classified_id, title, description, category_id
。
我试图在每个类别中提取分类数量。所以它看起来像这样。
我尝试了这样的尝试:
enter $catquery = mysql_query("SELECT * FROM categories WHERE sub_id = '0' ORDER BY name ASC"); here
enter $catrows = mysql_num_rows($catquery); here
enter $catrows = mysql_num_rows($catquery); here
enter $query = "SELECT category_id, COUNT(title) AS `total` FROM classifieds WHERE classified_id = 'category_id' "; here
enter $result = mysql_query($query); here
enter while($row = mysql_fetch_assoc($result)){ $num_items_in_category[$row['category_id']] = $row['total']; here
enter } echo "<li><a href='category.php?cat=".$row['id']."'>".$row['name']. $row['total']. "</a></li>"; here
谢谢费拉斯
答案 0 :(得分:0)
COUNT是一个聚合函数,因此您可以一次获得所有计数。
我相信你要找的是
$query = "SELECT category-id, COUNT(title) AS `total` FROM classifieds WHERE classified-id = 'category-cat' GROUP BY category-id";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$num_items_in_category[$row['category-id']] = $row['total'];
}
这将为您提供关联数组,其中包含每个category-id
的记录数答案 1 :(得分:0)
你应该能够通过加入2个表来完成你想要的东西。
SELECT a.name, count(*) as cnt
FROM categories a
join classifieds b
on a.id = b.category_id
group by a.name