views:

49

answers:

3

I have a question on best practice for relational databases and hierarchies. My question is, is it more sane to use text or int (id) based hierarchies?

I have a hierarchy, but it is not an id based one. The hierarchy is based on text e.g. 'level1', 'level2' as opposed to id1, id2

I use mysql and also solr for managing my data.

At the moment I have kept the text hierarchy, so could use that if I want to. But it seems healthier allround to create an id hierarchy (which I have also done). Int (id) hierarchies also seem faster and are not really prone to un-normalized data (I never have to trim() ids etc.)

Any thoughts on this are much appreciated. It would be interesting to find out what others feel is best practice.

Cheers

Ke

+1  A: 

I prefer to use ints - they are faster and smaller and do not need to be changed like a text based one might, since they contain no sematic meaning.

Ray
Im so glad you said this :). Im not a total noob, but also not a DB wizzkid either. I thought i was going in the right direction, speed is essential and Int's also seem the best way to keep a stringent relationship between hierarchies. Changing this would also be a big workaround to my app so really glad you feel this is the best way too.I dont know what I would do without stackoveflow. Hope you have an excellent day.
Ke
+1  A: 

if you use a id based hierarchy, will have better performance. but you can use two columns in your db that reserve two codes for you (IDCode and Code). this code made like this :

Child Code = IDCode + Parent Code

make attention that IDCode is unique.

this solution isn't good because you need some operations to process this work.

masoud ramezani
+1  A: 

I tend to use both, if I need to fetch subtrees.

Rows have 2 int columns consisting of an id and a parentId. This makes up the tree structure.

In addition I also have a textual level, representing the indexes of the parent line. e.g. a row with idName="44.21.31" would have an id of 31, a parent id of 21 and its grand parent would have an id of 44. This way you can fetch subtrees, `where idName like "44.21.%" would fetch every child, grand child and so on of the row with id 21.

That does break normal form though, there's now redundant information about the id of an entity - but it can be worth it, especially for db systems that doesn't otherwise suport hierarcical structures.

leeeroy
I have kept both just like you mention, so if i need to use text info then it is possible. Thanks for this, really clears things up for me. I will see how I go, if i run into speed problems, i guess i can always remove the redundant data . Thanks v much for these answers.
Ke