Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Sql-Self-Join-Abfrage? Wie bekomme ich Kategorien Unterkategorien?

Für eine maximale Tiefe von 6 (einschließlich Wurzel) können Sie dies verwenden

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

Erweitern Sie das Muster nach Bedarf für längere maximale Tiefen.