how do I get a recursive result by querying a self

2019-07-31 20:16发布

问题:

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

回答1:

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.