duanhongyi2964 2014-05-04 13:03 采纳率: 100%
浏览 28
已采纳

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

Im looking to create a ul list of categories and its sub categories (with count) related to the users search.

Example. if you was to go to ebay and search mac book pro, on the left it would show

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

I have 2 tables:

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)

I have spent the last few hours searching but havent found what im looking for.

Regards
Shane

  • 写回答

2条回答 默认 最新

  • doushuo2834 2014-05-04 13:44
    关注

    I think you can get what you want just using with rollup. The problem is that the sum will appear after the base rows:

      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
    

    To get it before, try this:

    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条)

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?