I have the following table. I am actually designing a simple chat, so, we have the user_id (the person who sends the message) and user_id_to (the person who receives the message).
| id | user_id | user_id_to | message | send_date |
|---|---|---|---|---|
| 1 | 1 | 2 | test 1 | 01-2-2023 |
| 2 | 2 | 1 | test 2 | 02-2-2023 |
| 3 | 3 | 1 | test 3 | 03-2-2023 |
| 4 | 1 | 2 | test 4 | 05-3-2023 |
| 5 | 2 | 1 | test 5 | 08-3-2023 |
| 6 | 3 | 1 | test 6 | 10-3-2023 |
| 7 | 4 | 1 | test 7 | 11-3-2023 |
| 8 | 5 | 1 | test 8 | 13-3-2023 |
| 9 | 5 | 1 | test 9 | 15-3-2023 |
| 10 | 5 | 1 | test 10 | 20-3-2023 |
| 11 | 1 | 3 | test 11 | 22-3-2023 |
I want to be able to select the distinct user (grouped by user), and message, order by max send_date.
So, with the above data, the following should be the result.
| id | user_id | user_id_to | message | send_date |
|---|---|---|---|---|
| 11 | 1 | 3 | test 11 | 22-3-2023 |
| 10 | 5 | 1 | test 10 | 20-3-2023 |
| 7 | 4 | 1 | test 7 | 11-3-2023 |
| 6 | 3 | 1 | test 6 | 10-3-2023 |
| 5 | 2 | 1 | test 5 | 08-3-2023 |
I need to use Laravel Eloquent, because with that I can use with('user', 'user_to') to select the users data together.
Answer provided by Karl Hill works, but it didn't select the message column. How can I also select the message column?
Please help.
I am assuming that you want the latest chat for each distinct pair of users. I am also assuming that all chat between (1, 2) and (2, 1) is considered one conversation.
To get the top-1-per-group you can use a
not existsquery with a twist:Demo on DB<>Fiddle
The fiddle also contains a
row_numbersolution if your RDBMS supports it.The eloquent code to produce the above query would be: