php – last mysql message for each friend

I found a similar problem here:
MySQL receives the latest chat messages

However, I only receive with the solution the last message from or to the user.

Well, that's my starting point:

Whenever the user sends a message himself, a database entry is created as follows.
Sender: ID in column A (own ID)
Recipient: ID in column B (friend)
Text: Column Text

Whenever the user receives a message, a database entry is created as follows.
Sender: ID in column A (friend)
Recipient: ID in column B (own ID)
Text: Column Text

Click here to view all the information about the manufacturer. Click here to find out more about associations and social partners.

Book Code:

$ query1 = "CHOOSE as zeit, text as msg, U1 as chat type, A as friend, ID as identifier
From Nachrichten
O ID IN (
SELECT MAX (ID)
From Nachrichten
O A = $ person & # 39;
GROUP BY B)
ORDER BY DESC ID ";

$ query2 = "SELECT Zeit as zeit, Text as msg," U2 "as chat type, B as friend, ID as identifier
From Nachrichten
O ID IN (
SELECT MAX (ID)
From Nachrichten
O B = $ person & # 39;
GROUP BY A)
ORDER BY DESC ID ";
$ ergebnisa = mysql_query ("SELECT *
OF
(
($ query1)
UNION ALL
($ query2)
) t
ORDER BY t.Zeit DESC LIMIT 5 ");

Problem for example:

User 1 sends the user 2 the message "Hello". (Database: A> 1, B> ​​2)
The user 2 sends to the user 1 the message "Good evening". (Database: A> 2, B> A)

Suppose the two messages are the most recent.
Both messages are now displayed as the most recent ones, although in fact only the second message should be displayed because the previous message is also new but belongs to the same friend.