Note that there are some explanatory texts on larger screens.

plurals
  1. POHierarchical table - how to get paths of the items [linked lists in MySQL]
    primarykey
    data
    text
    <p>I have a hierarchical table in MySQL: <code>parent</code> field of each item points to the <code>id</code> field of its parent item. For each item I can get the list of all its parents [regardless the depth] using the <a href="http://explainextended.com/2009/07/20/hierarchical-data-in-mysql-parents-and-children-in-one-query/" rel="nofollow noreferrer">query described here</a>. With <code>GROUP_CONCAT</code> I get the full path as a single string:</p> <pre><code>SELECT GROUP_CONCAT(_id SEPARATOR ' &gt; ') FROM ( SELECT @r AS _id, ( SELECT @r := parent FROM t_hierarchy WHERE id = _id ) AS parent, @l := @l + 1 AS lvl FROM ( SELECT @r := 200, @l := 0 ) vars, t_hierarchy h WHERE @r &lt;&gt; 0 ORDER BY lvl DESC ) x </code></pre> <p>I can make this work only if the <code>id</code> of the item is fixed [it's <code>200</code> in this case].</p> <p>I want to do the same for all rows: retrieve the whole table with one additional field (<code>path</code>) which will display the full path. The only solution that comes to my mind is to wrap this query in another select, set a temporary variable <code>@id</code> and use it inside the subquery. But it doesn't work. I get <code>NULL</code>s in the <code>path</code> field.</p> <pre><code>SELECT @id := id, parent, ( SELECT GROUP_CONCAT(_id SEPARATOR ' &gt; ') FROM ( SELECT @r AS _id, ( SELECT @r := parent FROM t_hierarchy WHERE id = _id ) AS parent, @l := @l + 1 AS lvl FROM ( SELECT @r := @id, @l := 0 ) vars, t_hierarchy h WHERE @r &lt;&gt; 0 ORDER BY lvl DESC ) x ) as path FROM t_hierarchy </code></pre> <p><strong>P.S.</strong> I know I can store the paths in a separate field and update them when inserting/updating, but I need a solution based on the <em>linked list technique</em>.</p> <p><strong>UPDATE:</strong> I would like to see a solution that will not use recursion or constructs like <code>for</code> and <code>while</code>. The above method for finding paths doesn't use any loops or functions. I want to find a solution in the same logic. Or, if it's impossible, please try to explain why!</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.
 

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