I have a table with the following key fields: commentid, comment, time, parentid
The comments are of two types, regular and replies. Regular have parentid 0; replies have parentid equal to the commentid they reply to.
I thought I had this figured out with group by and orderby but my idea didn’t work and I’m now struggling as my knowledge of sql is rudimentary.
I want it to display by time DESC except that I would like those with the same parentid grouped together and within that parentid, that they also be be sorted by time. I am allowing only one level of reply.
As an example, I would like following order:
time3 commentid3 parentid0
time2 commentid2 parentid0
parentid2 commentid4 time4 (this one is a reply)
parentid2 commentid5 time5 (this one also reply)
time1 comment1 parentid0
I tried SELECT * from comments GROUP BY parentid ORDER BY TIME DESC but this did not work. If needed, I can add another column. Any suggestions would be appreciated! Thx.
I’m making a few assumptions here. I’m assuming your commentid is an auto-incrementing id, so that would mean that the insert order would be from oldest to newest. This will not work if you are not using auto-incrementing ids or if you have some kind of partial-save functionality with these tables. So it’s kind of fragile.
I’m also assuming parent_id is null if it is the parent.
Anyway to add some more information.
Group Byis not what you want to use because it will group all rows by the grouping column into one row.Group Byis usually used for aggregate calculations such as counting or summing the values in rows, etc.EDIT:
I updated the query to sort by time asc, which will put the regular comment first and then the replies below the parent comment from oldest to newest.