title: MySql: Select last inserted value with GROUP BY and MAX
body: <p>I have a table called message with 5 columns. The primary key is message_id which is auto incremented. <a href="https://i.stack.imgur.com/dxLJq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dxLJq.jpg" alt="enter image description here"></a></p>
  
  <p>I am trying to select and display the last inserted message which has a related_message id of 26 by using Group By and Max. <br/> So I want to select everything from the table with only the last inserted message which is "stackoverflow".
  <br/><br/>
  I tried using various methods but to no avail.</p>
  
  <pre><code>SELECT *
     FROM message
     WHERE person_send_id = :person_send_id OR person_receive_id = :person_receive_id 
     AND related_message IN (SELECT MAX(related_message) FROM message GROUP BY related_message DESC)
     ORDER BY message_id DESC
  </code></pre>
  
  <p>Method 2</p>
  
  <pre><code>SELECT message_id, message, person_send_id, person_receive_id, max(related_message) as `related_message`
     FROM message
     WHERE person_send_id = :person_send_id OR person_receive_id = :person_receive_id
     GROUP BY related_message DESC
     ORDER BY message_id DESC
  </code></pre>
  
  <p><br/></p>
  
  <h2>Solution with the help of DarbyM</h2>
  
  <pre><code>SELECT m1.*
    FROM message m1
    JOIN (SELECT MAX(message_id) AS messageID
          FROM message
          Group By related_message) max
    ON max.messageID = m1.message_id 
    WHERE person_send_id = :person_send_id OR person_receive_id = :person_receive_id 
  </code></pre>