0

Here's the table structure

id | name | parent_id
1    fruit      0
2    apple      1
3    banana     1
4    orange     1
5    vegetable  0
6    carrot     5
7    tomato     5

I need get every row where a parent_id is 0, but I also need to to set an array on each row which is equal to 0 with the name of all it's children.

So I would have something like:

id = 1, name = fruit, children = [apple, banana, orange]

I'm aware there are better table structures but I must use the table structure stated.

I've tried getting all rows from the db then looping through them, if parent_id = 0 then push that to an array, otherwise it's a child so find parent in array and add it to that.

But there must be a better way?

0

4 Answers 4

1

I thinks you should use:

SELECT pr.id, pr.name, ( SELECT GROUP_CONCAT(name) FROM test as ch WHERE ch.parent_id = pr.id GROUP BY ch.parent_id ) AS children FROM test as pr WHERE parent_id = 0

Sign up to request clarification or add additional context in comments.

2 Comments

Very good. Thanks. Is there a way to include a string inside the children field? eg. we have apple,banana,pear etc. I woudl like to put in name:apple, name: banana
You use: GROUP_CONCAT('name:', name)
1

Without thinking about performance or beauty:

SELECT t.id, name, (
  SELECT GROUP_CONCAT(name) FROM table WHERE parent_id = t.id GROUP BY parent_id
) AS children 
FROM table t
WHERE parent_id = 0

2 Comments

small mistake in the inner select. parent_id shouldn't be 0, it should be equal to id from outer select.
give the outer table an alias and use its alias.id for the inner select. edited his answer
1

Avoiding a sub query, just using a self join the following should do it:-

SELECT t1.id, t1.name, GROUP_CONCAT(CONCAT('name:', t2.name)) 
FROM test t1
LEFT OUTER JOIN test t2
ON t1.id = t2.parent_id
WHERE t1.parent_id = 0
GROUP BY t1.id, t1.name

SQL fiddle for it:-

http://www.sqlfiddle.com/#!2/d4479a/1

1 Comment

this is even a better solution
0

I had come across a similar issue, where I had to fetch all subordinates of a user in a recursive manner. We wrote a function where we loop through each of the child records recursively until we reach the final subordinate. We keep on concatenating the subbordinates we find in each loop.

Hope through this you can think of a solution and resolve your problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.