Note that there are some explanatory texts on larger screens.

plurals
  1. PORemoving duplicate results from MySQL query
    primarykey
    data
    text
    <p>I have two mysql tables Users &amp; Messages. Please will you help me to create an sql query which returns only the most recent message either sent or received by the logged in user Mike ( user_id=1 ) along with the message_id, message_text &amp; first_name of the person who the message was sent to or received from. Ordered by message_id in descending order. </p> <p>So far i have the query:-</p> <pre><code>SELECT message_id, first_name, message_text FROM tbl_users, tbl_messages WHERE (tbl_users.user_id = tbl_messages.sender_id AND tbl_messages.receiver_id = 1 OR tbl_users.user_id = tbl_messages.receiver_id AND tbl_messages.sender_id = 1) GROUP BY tbl_users.first_name ORDER BY message_id DESC </code></pre> <p>Which gives the result in the image below. It seems the ORDER BY is being ignored</p> <p><img src="https://i.stack.imgur.com/XLDlq.gif" alt="Group by result"></p> <p>Thank you in advance</p> <p>tbl_users</p> <pre><code>--------------------------- | user_id | first_name | --------------------------- | 1 | Mike | | 2 | John | | 3 | George | | 4 | Peter | | 5 | Sarah | --------------------------- </code></pre> <p>tbl_messages</p> <pre><code>---------------------------------------------------------------- | message_id | sender_id | receiver_id | message_text | ---------------------------------------------------------------- | 1 | 2 | 1 | Hello | | 2 | 3 | 1 | How are you | | 3 | 1 | 5 | Hi there | | 4 | 2 | 1 | Greetings | | 5 | 1 | 4 | Good day | | 6 | 3 | 1 | Hi | | 7 | 5 | 1 | A message | | 8 | 5 | 4 | Good morning | | 9 | 1 | 5 | Hello dear | | 10 | 1 | 3 | Howdy | ---------------------------------------------------------------- </code></pre> <p>Desired result</p> <pre><code>---------------------------------------------- | message_id | first_name | message_text | ---------------------------------------------- | 10 | George | Howdy | | 9 | Sarah | Hello dear | | 5 | Peter | Good day | | 4 | John | Greetings | ---------------------------------------------- </code></pre> <p>Database is available <a href="http://zimpeople.com/sample_db.sql" rel="nofollow noreferrer">here</a></p>
    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