I have some hierarchical data (currently 6 levels). Each level has different attributes.
I added a separate table for each level and added a foreign key for parent level in each table. But I don’t know if it is the right approach.
Level1: id, ColA, ColB, ColC
Level2: id, ColD, ColE, ColF, level1_Id
Level3: id, ColG, ColH, level2_Id
Level4: id, ColI, ColJ, ColK, ColL, level3_Id
Level5: id, ColM, level4_Id
Level6: id, ColN, ColO, level5_Id
There will come additional levels in time. Therefore the design must be flexible so that I can add or remove some levels. Of course performance must be preserved.
Which design should I follow?
I am afraid, it is not the best way, in the sense that it is not flexible enough to give you unlimited levels and performance.
This problem is called “Hierarchical Data Model”, there are a few ways to implement it. Most portable format is called “Nested Sets” model. Other models are Adjacency Model, and the vendor specific models from Oracle and Microsoft.
Here is the stuff that can get you started
http://www.evanpetersen.com/item/nested-sets.html
http://www.sqlsummit.com/AdjacencyList.htm