首页 > 解决方案 > mysql 从同一个表中选择类别 e 子类别

问题描述

我有下表称为“产品”:

id INT 11
product_name VARCHAR 255
category VARCHAR 255
subcategory VARCHAR 255
subsubcategory VARCHAR 255

我想在一个查询中阅读所有类别、子类别和子子类别(每个类别仅一次)。

现在我有以下查询,但我不确定它是否有效:

SELECT category, subcategory, subsubcategory FROM products WHERE category != '' GROUP by category, subcategory, subsubcategory ORDER by category ASC, subcategory ASC, subsubcategory ASC

输出应该是这样的:

clothes (main category)
clothes > pants (sub category)
clothes > pants > man (sub sub category)
clothes > pants > woman
clothes > skirt
jewelry
jewelry > necklace

标签: phpmysqlselect

解决方案


你可以做:

select category as rendered from products
union all 
select concat(category, ' > ', subcategory) from products
union all 
select concat(category, ' > ', subcategory, ' > ', subsubcategory) from products
order by rendered

推荐阅读