What is the algorithm behind nested comments?

*爱你&永不变心* 提交于 2019-12-03 08:29:35

AS @Rafe said, the actual storage is pretty easy, it would be something like:

|  id  |   name   | parent |
|  1   | comment1 |    0   |
|  2   | comment2 |    1   |
|  3   | comment3 |    2   |
|  4   | comment4 |    1   |
|  5   | comment5 |    4   |
|  6   | comment6 |    4   |
|  7   | comment7 |    6   |
|  8   | comment8 |    7   |
|  9   | comment9 |    0   |

Of course actually getting information from this is (arguably) the hard part. You can of course get the children of a comment with something like: SELECT * FROM table WHERE parent='4' will give you all the children of comment4. But counting children, listing all the children in hierarchical order would be a bit harder. Other answers may provide more information on that.

It is called hierarchy. Each comment either has no parent comment, or has one parent comment. This way you can display every "top level" comment (thanks to the fact they have no parent comments), then child comments for each of them etc. etc.

And the database structure may look like this for comments table:

  • id field identifying single comment,
  • parent_id being set to parent's ID or not set (set to NULL or set to 0),
  • created - timestamp for comment creation,
  • content - actual comment content,
  • any additional field you need,

Pretty much what @Rafe Kettler noted - comments can have parent columns. However, if you want a more detailed and in-depth algorithm to use as a pattern for your implementation, take a look at this message threading algorithm.

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