-1

Here is my table structure

message_id sender_id receiver_id message
-----------------------------------------
   1         2          1         Hi 1
   2         1          2         Hi 2
   3         2          1         Hi 3
   4         1          2         Hi 4
   5         3          1         Hi 5

It is my query

 select * 
 from message 
 where receiver_id = '1' 
 GROUP BY sender_id 
 ORDER BY message_id DESC

Result is:

5 Hi 5
1 Hi 1

But My expect result is

5 Hi 5
3 Hi 3

What is the actual query?

Mohsen Shakibafar
  • 254
  • 1
  • 2
  • 15

1 Answers1

0

In your situation below SQL can provide your result. But check the performance for large data.

MAX will return 1 row for each grouped value.First we get message_id after that we get message from join query.So:

SELECT tb1.message_id, 
       tb1.message 
FROM   message tb1 
       INNER JOIN(SELECT Max(message_id) AS mid 
                  FROM   message 
                  WHERE  receiver_id = 1 
                  GROUP  BY sender_id) AS tb2 
               ON tb1.message_id = tb2.mid 

From the MySQL Docs:

MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. ... You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Sorting of the result set occurs after values have been chosen, and ORDER BY does not affect which values the server chooses.

Mohsen Shakibafar
  • 254
  • 1
  • 2
  • 15