Another SQL Question - Printable Version -Shoutbox (https://shoutbox.menthix.net) +-- Forum: MsgHelp Archive (/forumdisplay.php?fid=58) +--- Forum: Skype & Technology (/forumdisplay.php?fid=9) +---- Forum: Tech Talk (/forumdisplay.php?fid=17) +----- Thread: Another SQL Question (/showthread.php?tid=56630) Another SQL Question by Dempsey on 03-09-2006 at 05:21 PM
Well this is kind of a follow-on from my other thread: Number Range Query but it's a different problem now. code:Firstly it finds the records where M1PNON has the order number of 573 and returns a list of the matching M1ON numbers. Then it finds all the records that have their M1PNON field as one of the list just retireved. This is working fine, but I have just found out that I need to do it another level deep as well, but I'm confused as to how. Anyone have any pointers? I havent explained it very well, I'll post some sample data: code: records 1 and 2 are top level parents. 3 and 4 are child records of record 1 and 5 is a child of number 2. The query i have above can currently retireve both the parents and the first children, but it won't return a childs child, such as 6 and 7 which are children of record 5. So what do I need to add to the query to also make it retrieve the third level? Is it another IN statement? If so where exactly? Thanks for any help RE: Another SQL Question by Adeptus on 03-09-2006 at 05:46 PM
Do you only want to include one more level (easy), or did you just use that for illustration and really want to recursively follow the parent-child relationship chain and get all child records there are, arbitrary number of levels deep (hard)? RE: Another SQL Question by Dempsey on 03-09-2006 at 05:48 PM
Yea its just one more level, i thought there was only ever going to be two, but I just found out its actually three. RE: Another SQL Question by Adeptus on 03-09-2006 at 06:31 PM
Ok then. code: This is a self join -- where you join the same table to itself -- and as such, you have to alias your table names. Although most people use very short aliases, I chose descriptive longer ones here, to illustrate what's going on. This does exactly what your query does, but is a lot more readable. It is also very easy to have it dig one level deeper: you just add another self join: code: This would get you the next level of child rows. If you want both levels returned in the same resultset, just UNION ALL the two together: code: Hope that helps. RE: Another SQL Question by Dempsey on 03-10-2006 at 09:14 AM
Thanks, that sounds like that would do exactly what I need, except I'm not sure if I can use it. code:Thanks for the help RE: Another SQL Question by Adeptus on 03-10-2006 at 03:00 PM
Whatever works is good (and I hate these query setup dialogs)! |