问题
I want to learn the comment displaying algorithm behind Reddit. How is a comment related with its child and so on? How they are stored in the database?
Lets say
comment1
-comment2
--comment3
-comment4
--comment5
--comment6
---comment7
----comment8
comment9
How to display comment5 which is after comment4 which is after comment1? What is the idea behind this sequencing? And how to relate them in the database?
回答1:
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.
回答2:
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 toNULL
or set to0
),created
- timestamp for comment creation,content
- actual comment content,- any additional field you need,
回答3:
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.
来源:https://stackoverflow.com/questions/7197860/what-is-the-algorithm-behind-nested-comments