0

I have a table like

    id | parent_id
    -----------------
    55
    56    55
    57    55
    58    56
    59    57
    60    59
    61    60
    

Now when i select 55 i need all of its children and sub children. How to get that.

Like,

    55->56->58 
    ->57->59->60->61
    

so i need 56,57,58,59,60,61

and when i select 60

    60->61
    

i need only 61.

How to retrieve it ?? Please give me idea. Thanks in advance.

  • 1
    what you have tried ...? – user1844933 Mar 12 '14 at 07:59
  • ya i have been trying since few days :( – user3409511 Mar 12 '14 at 08:00
  • eh so if you select 55 it prints out all of them? or what? – bountyh Mar 12 '14 at 08:02
  • I think your question isn't clear, why do you need this, i don't see any real-life situation where you should need something like this... – ReeCube Mar 12 '14 at 08:02
  • There are lots of reasons why you need this. It is a difficult problem that SQL doesn't address very well. Unfortunately MySQL lacks the features that other DBs offer to solve it. – Nate C-K Mar 12 '14 at 08:03
  • ya as 55 is parent of 56 and 57, similarly 56 is parent of 58 and so on. i need to get all of them when i select 55. – user3409511 Mar 12 '14 at 08:03
  • Have a look at this: http://stackoverflow.com/a/1136085/219155 – Nate C-K Mar 12 '14 at 08:04
  • Your question is basically a duplicate of this: http://stackoverflow.com/questions/11110363/how-to-write-a-mysql-query-that-will-return-children-nested-under-parents – Nate C-K Mar 12 '14 at 08:10
  • The upshot is that you can write a straight-up SQL query for this **if** you assume that there is a maximum number of allowed child levels. (You just do a bunch of self-joins.) A general solution that will go to any number of levels is much trickier. – Nate C-K Mar 12 '14 at 08:13

0 Answers0