根据父类别获取产品数量

时间:2017-06-30 05:44:15

标签: php mysql mysqli

我想根据类别计算产品数量,我的类别级别是第n级 我曾尝试过以下查询,但我没有按预期得到结果:

SELECT count(p.prod_id),c.cat_name_eng,c.cat_id FROM product p 
left join category c on c.cat_id = p.cat_id group by p.cat_id

示例数据:
category_table:

cat_id   name    parent_id
1       craft       0
2       company     0
3       test        1   
4       test1       3       
5       test2       2   
6       test3       4
7       test4       5

product_table:

prod_id     cat_id  
1           1   
2           6
3           6   
4           4
5           2
6           7

预期产出:

+----------+------------------------+
| Category | Count in Product Table |
+----------+------------------------+
| craft    |                      4 |
| company  |                      2 |
+----------+------------------------+

我不想要测试,test1,test2,test3和test4,因为

  1. test的parent_id = 1,即craft
  2. test1有parent_id = 3,即测试又有parent_id = 1, 即工艺
  3. test3具有parent_id = 4,即test1,其中parent_id = 3,即test 其中parent_id = 1,即工艺
  4. test2的parent_id = 2,即公司
  5. test4的parent_id = 5,即test2,其中parent_id = 2,即公司
  6. 因此计算测试,test1和test3将进入工艺类别计数。
    计数为test2和test4将计入公司类别。

0 个答案:

没有答案
相关问题