Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I use MySQL Join to sort forum threads by their last reply?
    primarykey
    data
    text
    <p>I'm having a bit of trouble with writing a query for this. I think I have the basic logic down, although I might not. What I want to do is get all the threads based on the board that the user is viewing, and then sort those threads based on the time of their last reply. The query doesn't return any error, it only gets the most recently updated thread.</p> <p>Here's my query:</p> <pre> $query = " SELECT t.child_id, t.thread_id, m.thread_id, m.message_id, m.date_posted FROM forum_threads AS t LEFT JOIN forum_messages AS m ON t.thread_id = m.thread_id WHERE t.child_id = ".$board_id." ORDER BY m.date_posted DESC LIMIT ".$starting.", ".$this->user['results_per_page']; </pre> <p>This is the query that is being returned:</p> <pre> SELECT t.child_id, t.thread_id, m.thread_id, m.message_id, m.date_posted FROM forum_threads AS t LEFT JOIN forum_messages AS m ON t.thread_id = m.thread_id WHERE t.child_id = 2 ORDER BY m.date_posted DESC LIMIT 0, 15 </pre> <p><img src="https://i.stack.imgur.com/mcO9I.gif" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/7BaCL.gif" alt="enter image description here"></p> <h1>Update</h1> <p>I have attempted to go with the idea suggested by ethrbunny, although I am completely lost with what is causing it to return an error.</p> <pre> $query = " SELECT t.board_id, t.thread_id FROM forum_threads AS t LEFT JOIN ( SELECT m.thread_id, m.message_id FROM forum_messages AS m WHERE m.thread_id = t.thread_id ORDER BY m.message_id DESC LIMIT 1 ) AS q WHERE t.board_id = ".$board_id." ORDER BY q.date_posted DESC LIMIT ".$starting.", ".$this->user['results_per_page']; </pre> <pre>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE t.board_id = 4 ORDER BY q.date_posted DESC LIMIT' at line 11</pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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