I’m sorting some users by id (oldest to newest).
This is my accounts table:
Accounts
id | name |
---|---|
1 | James |
2 | Kirk |
3 | Roberto |
4 | Lars |
However, I need to improve this ordering by relating a second messages table.
Accounts_Messages
id | sender_id | receiver_id |
---|---|---|
1 | 1 | 4 |
2 | 1 | 2 |
3 | 1 | 3 |
In this case, users in Accounts table should be ordered by last messages.
This is the expected result:
Roberto;
Kirk;
Lars;
The question is: How can I sort the results of the first table by the id of the second?
I read that I need to use `JOIN` to relate these two tables, but I didn’t know how to apply it in this specific case.
Thank you, guys!
2
Answers
Hey use this MySQL query for your aspected result
this is what I understand by your question you need to sort the accounts by the id of the accounts_Message
I think you should try
if both Accounts and Accounts_Message has same column name id use
USING(id)
or the column name is different useON acc.id = am.id
instead