Search for last message from user grouped table in mysql

I have a personal message table on my site, and for a while I had a mailbox and a mailbox. I want to combine the Inbox / Help folder, displaying only the last message, either from a specific user or from him.

TL; DR: I want to show the last message, grouped by sending or from each user.

Table example

|  id | fromuser | fromid | touser | toid | message    |  timestamp            |
--------------------------------------------------------------------------------
|  1  | user1    |  1     | user2  |  2   | Hello..    |  2015-01-01 00:00:00  |
|  2  | user1    |  1     | user3  |  3   | okay...    |  2015-01-02 00:00:00  |
|  3  | user3    |  3     | user1  |  1   | not....    |  2015-01-03 00:00:00  |
|  4  | user2    |  2     | user3  |  3   | New....    |  2015-01-04 00:00:00  |
|  5  | user2    |  2     | user1  |  1   | With.....  |  2015-01-05 00:00:00  |
--------------------------------------------------------------------------------

The result I'm looking for when user 1

|  id | fromuser | fromid | touser | toid | message    |  timestamp            |
--------------------------------------------------------------------------------
|  3  | user3    |  3     | user1  |  1   | not....    |  2015-01-03 00:00:00  |
|  5  | user2    |  2     | user1  |  1   | With.....  |  2015-01-05 00:00:00  |
--------------------------------------------------------------------------------

Using the code below, I can make it show one message to or from one user, but it shows the oldest message, not the newest.

mysql_query("SELECT m1.*, users.id AS userid, users.username 
    FROM pm AS m1, pm AS m2, users 
    WHERE ((m1.fromuser='".$_SESSION['userName']."' AND users.id=m1.toid) 
    OR (m1.touser='".$_SESSION['userName']."' AND users.id=m1.fromid)) 
    AND m2.id=m1.id ORDER BY timestamp DESC");
+4
source share
1

:

< >    *      m      (        1                   (mm.fromuser = m.fromuser mm.fromuser = m.touser) (mm.touser = m.touser mm.touser = m.fromuser)            mm.timestamp > m.timestamp       )        m.fromuser = 'user1' m.touser = 'user1';

.

, , , , , , . .

. .

select m.* 
  from messages m 
     left join messages m2 
       on ((m.fromuser = m2.fromuser and m.touser = m2.touser) 
           or (m.fromuser = m2.touser and m.touser = m2.fromuser)) 
         and m.timestamp < m2.timestamp 
  where (m.fromuser = 'user1' or m.touser = 'user1') 
  and m2.id is null;

, not exists, .

+3

Source: https://habr.com/ru/post/1584043/


All Articles