0

我有一张桌子categoriesid, name, subcategory_id, parent_id. 另一个表classifieds有:classified_id, title, description, category_id

我正在尝试提取每个类别中的分类广告数量。所以它看起来像这样。

  • 配件(10)
  • 汽车(15)
  • 约会(12)

我试了一下:

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

谢谢各位

4

2 回答 2

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']; 
}

这将为您提供关联数组,其中包含每个类别 ID 的记录数

于 2012-05-10T01:44:45.450 回答
0

通过加入 2 个表格,您应该能够完成您正在寻找的内容。

SELECT a.name, count(*) as cnt
FROM categories a
    join classifieds b
    on a.id = b.category_id
group by a.name
于 2012-05-10T01:46:02.653 回答