I have written a simple messaging system for a CMS I am developing and am having a hard time finding the best way to grab all the messages and their replies ordered by the newest (message or reply).
I have a table called “messages” that has the fields:
*id, active[1,0], subject, message, datetime, user_from, user_to, reply_id*
It’s all straight forward and the *reply_id* is empty for main level messages and contains the parent id for replies. I am at a loss for how to write the SQL to grab all the main level messages in datetime DESC order based on themselves AND their replies. I’m sure it’s done with a UNION of some sort but my SQL skills are lacking. And if the same SELECT can give a count of the replies within each main level message that would be amazing!
Any help would be greatly appreciated!
It’s late and I’m tired but I think you could try something like that:
EDIT: fixed query
EDIT2: now includes messages without any replies