Jump to content

[SOLVED] Return multiple levels from same table


Recommended Posts

I have a groups table that sort of has this structure:

 

group_id PK

parent_group_id FK points to group_id of same group table

group_name

ect...

 

The parent_group_id gives ownership of a group to another group and this can continue down several levels.

 

Now - Group_D has parent id pointing to Group_C who has a parent id pointing to Group_B who has parent id pointing to Group_A

 

If an object belongs to Group_D then it also belongs to Group_C and so belongs to B and so belongs to group A. 

 

What would be the most efficient way to return all of the groups that an object belongs to?

 

So - an Object belongs to Group D and so i want to return D, C, B, and A.

 

i've tried

 

select * from groups 
where group_id = [Group_D's group_id]
or group_id = (
                select parent_id from groups where group_id = [Group_D's group_id]
              )
or group_id = (
                select parent_id from groups where group_id = 
                  ( 
                    select parent_id from groups where group_id = [Group_D's group_id] 
                  )
              )
or group_id = (
                select parent_id from groups where group_id = 
                  (
                    select parent_id from groups where group_id = 
                      ( 
                        select parent_id from groups where group_id = [Group_D's group_id] 
                      ) 
                  )
              )

I can keep adding nested selects for each level I want to go up the chain but MySQL has an issue with this

when i get to the 4th or 5th level... it errors out.

 

Is there a better, more efficient way to do this that doesnt use all of the nested selects that wouldnt be too much for MySQL to handle?

Try This

Assuming you have month,finyear,id in a table named calendar

select month,finyear,id,

CASE month when "01" then "January"

when "02" then "February"

when "11" then "November"

when "12" then "December"

END

from calendar where year = "2005" order by month

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.