Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to represent trees and their content in MySQL?

I need to be able to store something like this: Structure

where the green is a template type, the gray is a field container type, and the white is field. (That being, a field has a label and some text, both mediumtext for simplicity; and a field container can store other field containers or text, and a template is a top-level field.)

Now, let's say I want to allow users to create any number of these structures, but it is unlikely to be more than say 10. And, of course, we need to be able to link data to it.

This is all to be able to store in a database an associative array that looks for the above like, in pseudo code:

my_template = {
  page_info => { description => 'hello!!!' },
  id => 0,
  content => { background_url => '12121.jpg', text => ...
}

Having an easy way to add a field to all data using the template when the template changes (say, we add a keywords to page_info) would be a big plus.

I can't figure this out at all, thanks a lot!

like image 229
Aaron Yodaiken Avatar asked Aug 15 '10 21:08

Aaron Yodaiken


People also ask

How do you represent a tree in SQL?

Most trees are represented using Parent/Child. The easiest way to migrate from a Parent/Child structure to a table using hierarchyid is to use a temporary column or a temporary table to keep track of the number of nodes at each level of the hierarchy.

How do I display the contents of a table in MySQL?

The first command you will need to use is the SELECT FROM MySQL statement that has the following syntax: SELECT * FROM table_name; This is a basic MySQL query which will tell the script to select all the records from the table_name table.

How trees are stored in data structure?

The standard method of storing hierarchical data is simple parent-child relationship. Each record in the database includes a —parent id—, and a recursive query through the records build the children, siblings, and levels of the tree.

Which command is used to display the structure of a table in MySQL?

Since we have tables in MySQL, so we will use the DESCRIBE command to show the structure of our table, such as column names, constraints on column names, etc. The DESC command is a short form of the DESCRIBE command.


1 Answers

There are several different ways to store heirarchical data structures (trees) in MySQL. You can for example choose:

  • Adjacency list
  • Nested sets
  • Path enumeration
  • Closure table

See Bill Karwin's presentation for more details on the pros and cons of each.

like image 179
Mark Byers Avatar answered Sep 28 '22 02:09

Mark Byers