Hi boulevard,
You didnt mention which database you are using. ORACLE support hierarchical relationship with CONNECT BY and PRIOR. But mySQL doesnt support this. You need to write recursion for this. Consider the following table to check how to use connect by.
create table test_connect_by ( parent number, child number, constraint uq_tcb unique (child) );
insert into test_connect_by values ( 5, 2); insert into test_connect_by values ( 5, 3); insert into test_connect_by values (18,11); insert into test_connect_by values (18, 7); insert into test_connect_by values (17, 9); insert into test_connect_by values (17, 8); insert into test_connect_by values (26,13); insert into test_connect_by values (26, 1); insert into test_connect_by values (26,12); insert into test_connect_by values (15,10); insert into test_connect_by values (15, 5); insert into test_connect_by values (38,15); insert into test_connect_by values (38,17); insert into test_connect_by values (38, 6); insert into test_connect_by values (null,38); insert into test_connect_by values (null,26); insert into test_connect_by values (null,16);
select lpad(' ',2*(level-1)) || to_char(child) s from test_connect_by start with parent is null connect by prior child = parent;
This query will yield result like this
38 15 10 5 2 3 17 9 8 6 26 13 1 12 16


- perl_lover

In reply to Re: sql adjacency list by perl_lover
in thread sql adjacency list by boulevard

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.