Recursion for 1 database query

This is actually not the best way to model hierarchical data within a relational database.

Your optimal solution is going to depend upon whether it’s only going to be two levels or if you’re looking at a multi-level menu structure.

If it’s just two levels, then you’re usually going to be better off with two separate tables. (In the general case, the two levels of menu are two different entities with two different behaviors. The root menu entries exist only to cause the submenu to be displayed, while the child menus are links to the target pages.)

If you have a multi-level menu, see the message and referenced links at Some modelling advice - #12 by KenWhitesell for some ideas of generalized ways to model hierarchical data in a relational database.

1 Like