我有一个数据库表,它具有以下形式
catID | category | parentID 1 | firstCategory | null 2 | SubCategory1 | 1 3 | SubCategory2 | 1 4 | subSub1 | 3
等等……
有多个级别的类别。可以使用什么查询来获取以下格式的记录:
catID | category 1 | firstCategory 2 | firstCategory/SubCategory1 3 | firstCategory/SubCategory2 4 | firstCategory/SubCategory2/subSub1
类别 ID 将是最后一个类别的 ID。如何编写查询以将类别连接到所有级别?不同类别的确切级别数是不同的吗?
我正在使用 mySQL。
最佳答案
对于最大深度为 6(包括根),你可以使用这个
select l0.catID,
concat(
case when l5.catID is null then '' else concat(l5.category, '/') end
, case when l4.catID is null then '' else concat(l4.category, '/') end
, case when l3.catID is null then '' else concat(l3.category, '/') end
, case when l2.catID is null then '' else concat(l2.category, '/') end
, case when l1.catID is null then '' else concat(l1.category, '/') end
, l0.category)
from catcat l0
left join catcat l1 on l0.parentID=l1.catID
left join catcat l2 on l1.parentID=l2.catID
left join catcat l3 on l2.parentID=l3.catID
left join catcat l4 on l3.parentID=l4.catID
left join catcat l5 on l4.parentID=l5.catID
根据需要扩展图案以获得更长的最大深度。
关于SQL自连接查询?如何获取类别子类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4995721/