0
I created a chat, and I have a query to display the other accounts of the site to start a conversation. I put a select all, and it displays all normally, but now I need to put an order by to sort them according to the most recent messages, so I had to put an Inner Join with the message table.
My select is like this:
SELECT contas.Key_User, contas.Login_User, contas.User_Image, chat.Key_User1, chat.Key_User2, chat.Date
FROM contas
INNER JOIN chat
ON contas.Key_User = chat.Key_User1 OR contas.Key_User = chat.Key_User2 OR contas.Key_User > 0
WHERE `Key_User` not like '".$_SESSION['Key_User']."'
ORDER BY chat.Date DESC
The Where is not to show the user’s own account. However, with Inner Join, now it repeats the accounts for every message there is of it, so if the user has ten messages in all, will appear the profile ten times, and wanted to limit to appear only once, or another way to give an order by the date of the message.
I tried to use distinct, but I could not fit the group by.
chat.Key_User1: Key_User do usuário logado
chat.Key_User2: Key_User do usuário que vai receber a mensagem.
It worked! Actually, I was still repeating, but only twice now, and I was able to solve it by taking out the chat.Key_user1 and chat.Key_user2 from GROUP BY. And I removed the chat.Key_user2 from SELECT as well, as you suggested, and it was perfect.
– ErickGermani
But for some reason, ORDER BY isn’t working. Whenever I give F5, it changes the order of the users, but it shouldn’t happen because there are no new messages. You know what could be?
– ErickGermani
It may occur that two users have a conversation at the same time, as the ordering is only by
chat.Date
it uses an internal criterion to sort data with the same date, one option is to add a secondary criterion in theGROUP BY
thus:ORDER BY chat.Date DESC, contas.Key_User
– Carlos Pacheco