我试图在 MySQL 中创建带有计数公式的类别/子类别分支,但没有成功。
我的产品存储在我的数据库中,如下所示:
product_id|parent category | child category | grandchild category |
1 | A | a | α |
2 | B | b | β |
3 | B | b | γ |
4 | B | c | δ |
等等...
我试图得到这样的输出:
array(
[0] => ([parent category][0] => 'A', [child category][0] => 'a', [gchild cat][0] => 'α', [total][0]=> 1, [total][1] => 1, [total][3]=> 1),
[1] => ([parent category][0] => 'B', [child category][0] => 'b', [child category][1] => 'c' [gchild cat][1] => 'β', [gchild cat][2] => 'γ', [total][0]=> 3, [total][1] => 2, [total][2]=> 1, [total][3]=> 1, [total][4]=> 1, [total][5]=> 1, [total][6]=> 1)
)
在 MySQL 中使用此代码:
SELECT parent_category, child_category, grandchild_category,
(
COUNT('parent_category')
) as total1,
(
COUNT('child_category')
) as total2,
(
COUNT('grandchild_category')
) as total3
FROM table
WHERE valid_product= '1'
GROUP BY parent_category, child_category, grandchild_category
ORDER BY parent_category
但显然 MySQL 不会合并计数并为每个类别组合输出一个子数组。
我还尝试使用以下格式进行输出:
array('title'=> 'B',
'total' => 3,
'child_category' => array(array('title' => 'b',
'total' => 2,
'grandchild_category' => array(
array('title' => 'β',
'total' => 1
),
array('title' => 'γ',
'total' => 1
)
)
),
array('title' => 'c',
'total' => 1,
'grandchild_category' => array(
array('title' => 'δ',
'total' => 1
)
),
)
)
)
但还是没有接近。 有人知道我会做什么吗?像这样的输出有最好的格式吗?
最佳答案
这不是类别-子类别的正确架构。
id | category | parent (foreign key to id)
1 | A | NULL
2 | B | NULL
3 | a | 1
4 | α | 3
5 | b | 2
6 | β | 5
7 | γ | 5
8 | c | NULL
9 | δ | 8
正确构建您的架构,以便您可以从全局提供的工具和解决方案中受益。
关于php - 类别子类别mysql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51759555/