Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want people to be able to reply to the replies (i.e. have a hierarchy of replies such as you would see in, say, an online message forum), then I would add an optional parent_comment_id field to the comments table.</p> <p>Your table would look like this</p> <pre><code>`CREATE TABLE IF NOT EXISTS `comments` ( `id` int(12) NOT NULL AUTO_INCREMENT, `parent_comment_id` int(12) NULL, `comment` text, `user_id` int(12) DEFAULT NULL, `topic_id` int(12) NOT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `user_id` (`user_id`), KEY `topic_id` (`topic_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=27 ;` </code></pre> <p>Your query showing all comments and replies would be something like:</p> <pre><code>SELECT c.id, c.comment, r.comment as reply, c.user_id, u.username, u.photo FROM (comments c) JOIN users u ON c.user_id = u.id LEFT JOIN comments r ON c.id = r.parent_comment_id WHERE c.topic_id = 9 </code></pre> <p>Note however that with this query your replies would also show up not only in the 'reply' column, but also in the 'comment' column as additional rows each with zero or more replies.</p> <p>To show the username of the users who replied to a comment, you will need to join twice to the users table (first for the user who posted the original comment, and again for the user(s) who replied). Try this query to show the usernames of the users who replied:</p> <pre><code>SELECT c.id, c.comment, c.user_id, u.username, u.photo, r.comment as reply, r.user_id as reply_user_id, u2.username as reply_username, u2.photo as reply_photo FROM (comment c) JOIN users u ON c.user_id = u.id LEFT JOIN comments r ON c.id = r.parent_comment_id JOIN users u2 ON r.user_id = u2.id WHERE c.topic_id = 9 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload