I need to order a list of comments so they appear in their threaded order.
Each comment has a:
- Top parent comment (for queries)
- Parent comment
- Indentation level
If I’m fetching the comments as a list, what would be the most efficient way of sorting it so each comment is below its parent?
It has to remain as a 1-dimensional list. I just want to rearrange the items. I’m trying this but it doesn’t work as the list is mutated during enumaration, breaking the counter:
i = 0;
for child in childList:
ii = 0;
for ch in childList:
if (ch.reply == child.id):
childList.insert(i+1, childList.pop(ii))
ii += 1;
i += 1;
So… you’ve got something like this?
This just a depth-first pre-order tree traversal.
As Harypyon suggests, storing the children is a more efficient way of viewing this problem than storing the parent and then computing the children.
EDIT:
Ok.. this is in a database and you (probably) want some SQL that produces the desired result?
You’ve got a table like something like this?
Unfortunately, MySQL doesn’t support recursive query syntac (neither the
with recursivecommon table expressions norconnect by), so this self referential schema, though simple and elegant, is not useful if you want to do the whole thing in a single query with arbitrary depth and all of the needed metadata.There are two solutions. First, you can emulate the recursive query by doing the equivalent of a common table query in python, or in MySQL using temporary tables, with each of the sub-selects as a separate actual query. The downside is that this is neither elegant (many sql queries) and wasteful, (extra data transmitted over the connection or stored on disk).
Another option is to is accept that the transitive closure of the tree of comments is simply not computable, but that you can still make do with a compromise. You most likely don’t want (or need) to show more than a hundred comments at a time, and you similarly don’t need to show a depth of more than, say, 5 levels of nesting. To get more information, you would Just run the same query with a different root comment. Thus, you end up with a query something like
Which will give you a good “batch” of comments, up to 5 levels deep.