Storing / Retrieving 'Tree Children'

Discussion in 'Databases' started by TwistMyArm, Mar 18, 2007.

  1. #1
    OK, so maybe not the greatest title, but here's what I'm doing: I have a database table of locations. Three columns, 'id', 'name' and 'parent'. Essentially, by putting in the correct information I'm storing a tree of locations.

    Now when someone wants to filter some information (it's basically a business guide) they can choose whatever 'level' of the tree they want... what I mean is, it's possible that the location they select may have children locations.

    A business is generally associated with the most precise ('tree deep') location as possible, but it needs to show up whenever the user is filtering on any of that location's parents.

    I'm hoping that some DB guru can tell me the best way to deal with this please. I know that I can essentially grab the location that the user has selected, find its children, find their children and so on and then find all businesses linked to ANY of those locations, but it's possible that as the tree gets bigger, well this will slow things down.

    I then started thinking of having a second table that essentially stores all children: one table stores the tree structure itself while this second one stores the fact that for node 'a', nodes 'b' through 'z' are 'descendants', possibly a number of levels descendant, of that node 'a'. Having said that, it doesn't seem very 'DB normalised' for me and I can see that this table may get pretty big, pretty quickly.

    So the big question: how have others approached this or how would you? Do I just suck it up and accept that I will either have an increasing number of queries to find all children or redundant data in another table, or is there some database magic I can do? Maybe there's some cool way to number the data, maybe?

    I don't mind changing the table structure if need be... I just want to know the best way to do it.

    Many thanks!
     
    TwistMyArm, Mar 18, 2007 IP