0

so we have:

table users

id name password parent_id

the first user have the id 1, and others have the parent_id 1, so I select all the users that have the parent_id == 1 - they are the childs of the user with 1, okay its all right, but now i need to select the users that have the parent_id of the selected before users with they id, if they exists of course

    user with id 1
   /      |     \
  /       |      \
 /        |       \
users with parent_id 1

user id 2    user id 3 id  user 4
|          |        |
|          |        |
|          |        |

and here is the same, I need to select all the users that have the parent_id 2, 3, 4 for each of those user, its is something like a pyramide(triangle) from the top to the bottom

So the question is how can i make a query that will select it in one shot, not in many queries by extracting the id and then make other query - its not good i think

do you have an idea??

Mister PHP
  • 307
  • 4
  • 17
  • please more clearify your question – Muhammad Raheel Jun 29 '12 at 08:01
  • 1
    [this](http://www.artfulsoftware.com/mysqlbook/sampler/mysqled1ch20.html) may help. afair is's not so simple in mysql, but can be made in postgres – k102 Jun 29 '12 at 08:02
  • 3
    MySQL doesn't support recursive functions, so it is not well suited to this adjacency list model of storing hierarchical data. You ought to consider restructuring your data to use either nested sets or closure tables. See [this answer](http://stackoverflow.com/a/192462/623041) for more information. – eggyal Jun 29 '12 at 08:03

2 Answers2

0

Here is a question, that covers your problem:
Is it possible to query a tree structure table in MySQL in a single query, to any depth?

Query below works only for finding children and grand-children of a single user and is a product of misunderstanding the question!

You could try joining user table on itself twice.

SELECT * FROM users as up 
JOIN users as u on up.id=u.parent_id 
JOIN users as uc on u.id=uc.parent_id 
WHERE up.id={$grandParentUserId}

Aliases: up = user's parent, u = user, us = user's child.
Definitely not a pretty solution, but it's a single request.

Community
  • 1
  • 1
Niemand
  • 346
  • 2
  • 10
0

I see you are using CI. You can have a look at this answer. Somewhat related to your question. You can select the users with NULL parent ID first and then populate their children

https://stackoverflow.com/a/9937130/876117

Community
  • 1
  • 1
Broncha
  • 3,794
  • 1
  • 24
  • 34