If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Recursive Table Query Help Needed .....Sorely

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 12-14-04, 18:08
Vmusic Vmusic is offline
Registered User
 
Join Date: Dec 2004
Posts: 54
Recursive Table Query Help Needed .....Sorely

Hi,
I have a recursive table and I need help with a query. The table is table of people and organizations. Sorry for the alignment but a sample is below:

party_id, party_type, first_nm, last_nm, org_nm, parent_id

22, ORGANIZATION, NULL, NULL, Smart Company, NULL (No parent)
45, PERSON, Jimmy, Smith, NULL, 22 (The parent here is party id 22)
59, PERSON, Johnny, BGood, NULL, 22 (The parent here is party id 22)

I want to write a query that retrieves a row and all its children through a search.


So in my example above, If Smart Company had ONLY 2 children rows, as shown my query would retrieve ALL 3 rows

The query will run as a search so the filter clause will contain WHERE org_nm LIKE '%Smart Co%' or whatever organization they're searching on.


This isn't for your faint of heart here......
THANKS!!!!
Vmusic
Reply With Quote
  #2 (permalink)  
Old 12-14-04, 18:49
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,534
when you say "a row and all its children" do you mean just those which are one level down in the hierarchy?
Code:
select org.party_id
     , org.party_type
     , org.first_nm
     , org.last_nm
     , org.org_nm
     , org.parent_id
  from yourtable as org
 where org.org_nm like '%Smart Co%'   
union all
select per.party_id
     , per.party_type
     , per.first_nm
     , per.last_nm
     , per.per_nm
     , per.parent_id
  from yourtable as org
inner
  join yourtable as per
    on org.party_id
     = per.parent_id  
 where org.org_nm like '%Smart Co%'
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On