Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>@Alex Martelli</code>'s answer is great! But it work only for one element at time (<code>WHERE name = 'Joan'</code>) If you take out the <code>WHERE</code> clause, the query will return all the root rows together...</p> <p>I changed a little bit for my situation, so it can show the entire tree for a table.</p> <p>table definition:</p> <pre><code>CREATE TABLE [dbo].[mar_categories] ( [category] int IDENTITY(1,1) NOT NULL, [name] varchar(50) NOT NULL, [level] int NOT NULL, [action] int NOT NULL, [parent] int NULL, CONSTRAINT [XPK_mar_categories] PRIMARY KEY([category]) ) </code></pre> <p>(<code>level</code> is literally the level of a category 0: root, 1: first level after root, ...)</p> <p>and the query:</p> <pre><code>WITH n(category, name, level, parent, concatenador) AS ( SELECT category, name, level, parent, '('+CONVERT(VARCHAR (MAX), category)+' - '+CONVERT(VARCHAR (MAX), level)+')' as concatenador FROM mar_categories WHERE parent is null UNION ALL SELECT m.category, m.name, m.level, m.parent, n.concatenador+' * ('+CONVERT (VARCHAR (MAX), case when ISNULL(m.parent, 0) = 0 then 0 else m.category END)+' - '+CONVERT(VARCHAR (MAX), m.level)+')' as concatenador FROM mar_categories as m, n WHERE n.category = m.parent ) SELECT distinct * FROM n ORDER BY concatenador asc </code></pre> <p>(You don't need to concatenate the <code>level</code> field, I did just to make more readable)</p> <p>the answer for this query should be something like:</p> <p><img src="https://i.stack.imgur.com/tPiTu.png" alt="sql return"></p> <p>I hope it helps someone!</p> <p>now, I'm wondering how to do this on MySQL... ^^</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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