0

For example, I have a table like this:

----------------------
| id | Name | Parent |
......................
| 1  | Joe  |  ''    |
| 2  | Alice|  ''    |
| 3  | Manny|  ''    |
| 4  | kid1 |  1     |
| 5  | kid2 |  1     |
| 6  | kid3 |  3     |

and I want to display it in a hierarchy manner like this:

| id | Name | Parent |
......................
| 1  | Joe  |  ''    |
| 4  | kid1 |  1     |
| 5  | kid2 |  1     |
| 2  | Alice|  ''    |
| 3  | Manny|  ''    |
| 6  | kid3 |  3     |

Can I do it using only SQL commands?


Thank you so much guys. I'm new to stackoverflow, yet I'm already amazed by how fast you have answered my question.

@amar duplantier, Thanks for the link it solved my problem!! I can't find that thread when I searched before. I'm sorry I didn't provide enough information for my question.

here's the code I use based on amar's link:

select  *
from Table a
order by
        case 
        when Parent = '' 
        then id 
        else    (
                select  id 
                from    Table parent 
                where   parent.id = a.Parent
                ) 
        end
DESC
Konthorn
  • 45
  • 6

3 Answers3

0

You didn't mention a database in particular, so allow me to provide a solution using Oracle.

In Oracle you can perform START WITH and CONNECTED BY:

select id, Name, Parent from your_table start with parent is null connect by prior id = parent;

Not all database have connected by, such as MySQL, but you can simulate it using functions: http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/

Alexandre Santos
  • 8,170
  • 10
  • 42
  • 64
0

Try Recurcive CTE:

WITH HierarchyTree (id, Name, Parent)
AS
(
-- Anchor member definition
    SELECT e.id, e.Name, e.Parent
    FROM MyTable AS e
    WHERE id = 1
    UNION ALL
-- Recursive member definition
    SELECT e.id, e.Name, e.Parent
    FROM MyTable AS e
    INNER JOIN HierarchyTree AS d
        ON e.Parent = d.id
)
SELECT id, Name, Parent
FROM HierarchyTree
GO
ttaaoossuuuu
  • 7,786
  • 3
  • 28
  • 58
0

If the '' in the Parent column mean empty string then

SELECT   *
FROM     table1
ORDER BY Concat(Parent, ID)
       , ID

will return a resultset with the order the OP want (if there is only only level of hierarchy)

Serpiton
  • 3,676
  • 3
  • 24
  • 35
  • wow, never thought of this method before. Yes this is working very good and short/not complex as well. Thanks! – Konthorn May 27 '14 at 08:09
  • @Konthorn it uses the fact that the string order for number is not the same of the number order, it's probably the first time that I used it on purpose and not only to demostrate the difference between the two – Serpiton May 27 '14 at 08:31