1

I have a self-referencing table 'comments' where comments.replyToId REFERENCES comments.ID.

My question is, how do I query a database with a self-referencing table to get a result that is properly ordered so that I can represent the result as a tree in PHP?

I've tried

select * from comments as comments_1 
left join comments as comments_2 
on comments_1.id = comments_2.replyToId

I'm trying to use the result of this in php

fenerlitk
  • 5,414
  • 9
  • 29
  • 39
  • @zerkms My question is, how do I query a database with a self-referencing table to get a result that is properly ordered so that I can represent the result as a tree in php ? I hope my question is clearer now... thanks – fenerlitk Jan 29 '12 at 21:34
  • ok so what's wrong with what you get out of this? – Nicolas78 Jan 29 '12 at 21:36
  • 1
    I found your question looking for answers, I didn't come up with the solution but seeing so little answers for this question I thought I would take the time to come to SO a link people to the solution, so others can solve this faster, kudos to Rolando, He is my personal DBA Hero for this clever solution. http://dba.stackexchange.com/questions/7147/find-highest-level-of-a-hierarchical-field-with-vs-without-ctes – Gabriel Acosta Apr 18 '13 at 14:13

1 Answers1

3

You're not going to get a recursive result out of MySQL directly. There was a similar discussion recently - it is maybe possible with some RDBMS using stored procedures etc, but not with out-of-the-box SQL (see How can I get ancestor ids for arbitrary recursion depth in one SQL query?).

What I do instead in similar cases: Get all comments without parents. Then, for each comment, get its children (if you store the "depth" of each comment you may get all these children and all children of the next layers with one SQL query). Store the children in the appropriate place in your tree structure, repeat.

If you need a more low-level, you'll prly need to share some code, explain your data structure, what you've tried so far etc., this is just the general approach.

Community
  • 1
  • 1
Nicolas78
  • 5,124
  • 1
  • 23
  • 41