2

So I have a table in a database filled with categories structured like this:

pk int: cat_id
int: parent_id
varchar: cat_name

A top level category has a null parent_id and there could be several levels of children. Basically, I am taking a search string and matching it against the category names, and if the category has parents then I want to display the full path in breadcrumb fashion for all matches. Here is pseudo code for what I am doing now:

search_string = whatever;
result = query db and find all category names matching "%whatever%";
foreach(result)
{
    parent_id = result[parent_id];
    result_path = result[cat_name];
    while(parent_id != null)
    {
        result2 = query db and find cat_id = parent_id;
        result_path = result2[cat_name] + " > " + result[path];
        parent_id = result2[parent_id];
    }
    print result_path;
}

Is there a more efficient way to do this other than the nested loop and database queries?

Thanks for any input.

4

1 に答える 1

0

What you have is a hierarchy stored as an adjacency list. Recursion is the only practical way to solve this, either in MySql or PHP.

If you are seriously looking for efficiencies for this particular query then store your hierarchy as nested sets. Be aware that this is a non-trivial exercise and will increase the cost of maintaining your data. It will also reduce the efficiency of other queries such as finding children.

There is plenty of info on this site and others about storing hierarchical data in RDMS.

于 2013-02-21T06:00:42.633 に答える