how do I get a recursive result by querying a self referencing table in mysql?

淺唱寂寞╮ 提交于 2019-12-24 08:23:35

问题


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.



来源:https://stackoverflow.com/questions/9056878/how-do-i-get-a-recursive-result-by-querying-a-self-referencing-table-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!