包含产品计数的相关类别和子类别

时间:2014-05-04 13:03:17

标签: php sql categories

我希望创建一个与用户搜索相关的类别及其子类别(带计数)的ul列表。

实施例。 如果你要去ebay并搜索mac book pro,左边会显示

Computers/Tablets & Networking (20 items)
   -Laptop & Desktop Accessories (5 items)
   -Laptops & Netbooks (15 items)

我有两张桌子:

Categories Table

id  |  category_name  |  parent_id
--------------------------------------
1   | computers       |     0
2   | apple           |     2
3   | microsoft       |     2
4   | accessories     |     0
5   | mouse           |     4
6   | keyboards       |     4
7   | printers        |     4

#############################################################

And Products Table

id  |  product_name  |  category_id
--------------------------------------
1   | macbook pro      |     2
2   | macbook air      |     2
3   | surface pro      |     3
4   | ipad             |     2
5   | backlit keyboard |     6
6   | mini keyboard    |     6
7   | 3 in 1 printer   |     7


some sql and php to disply:

computers (4)
  -apple (3)
  -microsoft (1)

accessories (3)
  -keyboards (2)
  -printers (1)
  -(dont show mouse because no mouses in products table)

我花了最后几个小时搜索,但还没找到我正在寻找的东西。

问候
沙恩

2 个答案:

答案 0 :(得分:1)

我认为只需使用with rollup即可获得所需内容。问题是总和将出现在基本行之后:

  select cp.category_name as parent_name, c.category_name, count(*) as numcategories
  from products p join
       categories c
       on p.categoryid = c.id join
       categories cp
       on c.parentid = cp.id
  group by cp.category_name, c.category_name with rollup

要获得它,请尝试:

select parent_name, category_name, numcategories
from (select cp.category_name as parent_name, c.category_name, count(*) as numcategories
      from products p join
           categories c
           on p.categoryid = c.id join
           categories cp
           on c.parentid = cp.id
      group by cp.category_name, c.category_name with rollup
     ) t
where category_name is not null
order by category_name,
         category_name is null desc;

答案 1 :(得分:0)

@Gordon Linoff使用第二个声明:

$result = mysqli_query($db,"select parent_name, category_name, counter from (select cp.category_name as parent_name, c.category_name, count(*) as counter from adverts p join categories c on p.category_id = c.id join categories cp on c.parent_id = cp.id group by cp.category_name, c.category_name with rollup) t where category_name is not null order by parent_name, counter DESC");
$count = mysqli_num_rows($result);

if($count >= 1){
   while($row = mysqli_fetch_array($result)) {

     if (empty($rowo['category_name'])) {

         $category_view = ("<strong>". $rowo['parent_name']. "</strong> (". $rowo['counter']. ")"); 

     }else{

        $category_view = ("". $rowo['category_name']. " (". $rowo['counter']. ")");

     }


     echo("<li>". $category_view ."</li>");


   } // while loop

}  // counter >= 1




Antiques (3)  
   -Fabric/ Textiles (2)  
   -Ethnographic Antiques (1)
Art (5)  
   -Photographs (4)  
   -Drawings (1)

再次感谢戈登。