Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL for hierarchical relationship

Tags:

sql

mysql

I've a table where products are categorised based on hierarchical relationship like a tree structure. I'm having to select a category and all subcategories at any level. See the picture below:

enter image description here

e.g. i want an sql statement that when i query passing the id=11, it returns me (19,20,21,22,23,24,25,26)

like image 363
Noor Avatar asked Jul 08 '12 11:07

Noor


People also ask

Which database is best for hierarchical data?

Examples of Hierarchical Database SystemsIBM's Information Management System (IMS) is an example of a hierarchical database system. Windows Registry is another such example. Another example that you may be aware of is XML data storage that we discussed earlier. XML has a root node enclosing one or more child nodes.

How do we display hierarchical relationship in data?

Hierarchical data is shown in tree graphs; so called because of their similarity to a tree's structure (though a tree which has been turned upside down so that the root is at the top and the branches form below it).


1 Answers

There are several different ways to store heirarchical data in MySQL. Check out Bill Karwin's presentation that demonstrates four options.

  • Adjacency List
  • Path Enumeration
  • Nested Sets
  • Closure Table

You are using the adjacency list model for storing heirarchical data, but unfortunately this is the hardest model you could choose for querying subtrees.

nested sets query subtree

Your options are:

  • Change to a different model.
  • Restrict queries to n levels deep.
  • Use a stored procedure to query recursively. For more information about this, see Quassnoi's series of articles - Hierarchical queries in MySQL.
like image 92
Mark Byers Avatar answered Sep 21 '22 12:09

Mark Byers