Question

I got the following Mysql Structure

categories tab
--------------------------
layer1 | layer2 | layer3
--------------------------
echo   | brain  |
echo   |        |
echo   | foo    |
echo   | brain  | diffuse
echo   | brain  | clear
echo   | cheesy | nuts
echo   | cheesy |   

I´ve tried to output the following Structure as a HTML list

  • echo

    • (...) brain

    • (...) cheesy

    • foo

(...) should be a hint for the user that brain and cheesy have also childelements to offer.

e.g. When he clicks on brain the following View should be shown:

  • echo

    • brain

      • clear

      • diffuse

    • (...) cheesy

    • foo

This drive me nuts ... tried so many GROUP/ORDER BY, UNION and CASE variants but I don´t get it -.-

Was it helpful?

Solution

Given the way you're storing the data, you probably can't do this in one SQL query. Or else it would be so brain-meltingly complicated that it's a bad idea to do so. Remember the advice of Brian Kernighan:

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

You can do the first query pretty easily:

SELECT layer1, layer2, COUNT(layer3) AS dotdotdot
FROM categories
WHERE layer1 = 'echo'
GROUP BY layer1, layer2

If dotdotdot is non-null, then there's a nonzero number of subcategories in layer 3.

If the user has highlighted "brain", then as you display the result of the first query in a loop, run one more query:

SELECT layer3
FROM categories
WHERE layer2 = 'brain'

And that's it. It may seem so dull to run two queries instead of finding some ingenious way of doing it all in one query, but you'd be surprised how frequently a complex problem becomes both simpler and more efficient when you break it down into smaller problems.

If you want something more streamlined, check out my presentation Models for Hierarchical Data with SQL and PHP. I show an example of the kind of problem you're trying to implement: selective expansion of a given level in a hierarchy. But I solve the problem by storing the data differently than you are.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top