I’m writing a script to handle comments similar to facebook’s status/replies. Basically, an item can have comments and users may reply to that comment (one level deep maximum).
My tables are set up as follows:
Comments: [ Comment_ID | User_ID | Content | etc...]
Comments_Reply: [ Comment_ID | Is_Reply_To ]
So if a user replies to comment #555 it appears in the comments table like a regular comment, then also gets a row in Comments_Reply with [ 555 | New Comment ID ]
How can I select the comments such that they are in the following order:
[ 555 | ....
[ New Comment that replies to 555
[556 | ....
[557 | ....
Etc… where the replies appear sequentially after the comment the reply to. I am using PHP & MySql.
Ok, I think I got what you want now. I don’t have a way to test the MYSQL version of this function quickly, but the SQLite version works great and, according to the documentation, the MySQL should work just as great. Might be a better way to do it on MySQL though.
SQLite:
SELECT a.*, IFNULL( b.Is_Reply_To, a.Comment_ID ) as Is_Reply_To FROM Comments a LEFT JOIN Comments_Reply b HAVING(Comment_ID) ORDER BY Is_Reply_To ASC, a.Comment_ID ASCMySQL
SELECT a.*, IF( IS NULL(b.Is_Reply_To), a.Comment_ID, b.Is_Reply_To ) as Is_Reply_To FROM Comments a LEFT JOIN Comments_Reply b HAVING(Comment_ID) ORDER BY Is_Reply_To ASC, a.Comment_ID ASCThis produces these results for my on SQLite.