Note that there are some explanatory texts on larger screens.

plurals
  1. POrecursive query for adjacency list to preorder tree traversal in SQL?
    primarykey
    data
    text
    <p>I am migrating data from one database schema to another. The old schema has a categorization system based on an adjacency list, with id, category, and parent_id. If one category is under a second, that category has the second's id as its parent id. For example:</p> <pre><code>+-------------+----------------------+--------+ | category_id | name | parent | +-------------+----------------------+--------+ | 1 | ELECTRONICS | NULL | | 2 | TELEVISIONS | 1 | | 3 | TUBE | 2 | | 4 | LCD | 2 | | 5 | PLASMA | 2 | | 6 | PORTABLE ELECTRONICS | 1 | | 7 | MP3 PLAYERS | 6 | | 8 | FLASH | 7 | | 9 | CD PLAYERS | 6 | | 10 | 2 WAY RADIOS | 6 | +-------------+----------------------+--------+ </code></pre> <p>The new schema has a modified preorder tree traversal algorithm:</p> <pre><code>+-------------+----------------------+-----+-----+ | category_id | name | lft | rgt | +-------------+----------------------+-----+-----+ | 1 | ELECTRONICS | 1 | 20 | | 2 | TELEVISIONS | 2 | 9 | | 3 | TUBE | 3 | 4 | | 4 | LCD | 5 | 6 | | 5 | PLASMA | 7 | 8 | | 6 | PORTABLE ELECTRONICS | 10 | 19 | | 7 | MP3 PLAYERS | 11 | 14 | | 8 | FLASH | 12 | 13 | | 9 | CD PLAYERS | 15 | 16 | | 10 | 2 WAY RADIOS | 17 | 18 | +-------------+----------------------+-----+-----+ </code></pre> <p>Examples taken from the article <a href="http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/" rel="nofollow">Managing Hierarchical Data in MySQL</a>.</p> <p>Anyhow, I'm capable or writing a php script with a recursive function that will migrate the adjacency list to the preorder tree structure. Basically for each row, it inserts it with a blank 'rgt' value, looks for children, applies the function recursively to them, keeping track of the counter, and then updates the 'rgt' value.</p> <p>But I want to do this in pure SQL. However, I don't know enough to get a foothold on it. For starters, I don't know if you can do this with a recursive query, or if there are other ways of doing it. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload