In MySql I have table:
idPost | idPostParent | postText | dateCreated |
1 | 1 | This is parent post no1 | 2012-01-01 12:00:00 |
2 | 2 | This is parent post no2 | 2012-01-02 13:00:00 |
3 | 1 | This is first reply on idPost:1 | 2012-01-02 13:30:00 |
4 | 4 | This is parent post no3 | 2012-01-04 10:00:00 |
5 | 2 | This is first reply on idPost:2 | 2012-01-04 11:00:00 |
6 | 1 | This is second reply on idPost:1 | 2012-01-05 15:00:00 |
7 | 2 | This is second reply on idPost:2 | 2012-01-06 17:00:00 |
NOTE:
- PARENT post is detected if idPost = idPostParent
- REPLY post is detedted if idPost <> idPostParent and reply is
related to post writen in idPostParent
I need SQL query for sorting and grouping record sets in table by some rules:
- Posts must be grouped by idPostParent (parent post first then its
replies) - The PARENT post that is latest entered OR have latest entered reply must be on the top.
The resultset should be:
idPost | idPostParent | postText | dateCreated |
2 | 2 | This is parent post no2 | 2012-01-02 13:00:00 |
5 | 2 | This is first reply on idPost:2 | 2012-01-04 11:00:00 |
7 | 2 | This is second reply on idPost:2 | 2012-01-06 17:00:00 |
1 | 1 | This is parent post no1 | 2012-01-01 12:00:00 |
3 | 1 | This is first reply on idPost:1 | 2012-01-02 13:30:00 |
6 | 1 | This is second reply on idPost:1 | 2012-01-05 15:00:00 |
4 | 4 | This is parent post no3 | 2012-01-04 10:00:00 |
REASON:
The PARENT post idPost=2 has latest entered reply post so its thread must be on the top of the table.
Thanks to anyone who may contribute to the solution!
Here’s one way:
Explanation:
The sub-query
selects the maximum date created per “thread” (
idPostParent).This is
LEFT JOINd to the mainpoststable, so that every thread has atime_of_newestfor that thread.We sort by
time_of_newestDESCENDING (this puts thread 2 in front of thread 1 in front of thread 4).Then, we sort by
idPost=idPostParent1 DESCin order to get parent posts in front of replies (parent posts have a 1 here and replies all have a 0, and since we sort descending parent posts go first).Finally, we sort by
dateCreated DESCto get the replies in order.