Note that there are some explanatory texts on larger screens.

plurals
  1. POSorting items in MPTT result set?
    primarykey
    data
    text
    <p>I'm using the <a href="http://www.zaachi.com/en/items/modified-preorder-tree-traversal-algoritmus-1.html" rel="nofollow noreferrer">MPTT</a> (modified preorder tree traversal) model to store hierarchical data in my MySQL table. (MPTT model: another description is <em>nested set model</em>.). My question is this: has anyone figured out a clever way to sort the results of a query on the tree? I could just go 'ORDER BY label', but then the result set will be sorted by label without respect to the nodes' place or depth in the tree.</p> <p>Here's an example of the query I use to retrieve the tree of an arbitrary node, with each node's depth:</p> <pre><code>SELECT node.id, (COUNT(parent.id) - (sub_tree.depth + 1)) AS depth FROM person AS node, person AS parent, person AS sub_parent, ( SELECT node.id, (COUNT(parent.id) - 1) AS depth FROM person AS node, person AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.id = 1 // that's my root object GROUP BY node.id, node.lft ORDER BY node.lft ) AS sub_tree WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt AND sub_parent.id = sub_tree.id GROUP BY node.id ORDER BY node.lft </code></pre> <p>As per <a href="http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/" rel="nofollow noreferrer">http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/</a>.</p> <p>Of course, this always orders items by their place in the nested set. What if I wanted to order them by, say, 'lastName' or 'accountBalance' or 'town' instead? Can that be done in MySQL, or do you folks think I'd have to resort to sorting the results in my scripting language?</p>
    singulars
    1. This table or related slice is empty.
    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.
    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