Get the latest message from each user in a table
Say my messages table looks something like this:
This means user 1 has sent a greeting to user 2, and user 2 has responded. User 1 has written to user 3, who has not responded.
This means that the latest messages in all conversations for user 1 should be messages 2 and 3. This can then grow exponentially. But what I want is to get the LATEST message in any conversation, regardless of if you are the sender or recipient.
How would I write a query for this? Using plain SQL it's been suggested to use a CTE but how would I do it in Drizzle?
9 Replies
Right now my query is
but this gives me all messages, like:
it seems to me like I should add some sort of "distinct" filter for the "sender"?
Do you want to get back an array of messages, or users with one message each?
Users with one message each, ideally, but either way really
Oh! I think that's easier, actually.
I might have some time Soon™ to take a look and see if I can get you the answer
Until then, you should try db.query stuff with relations
You might be able to figure it out yourself
Yeah i tried using relational queries as well but couldn't figure it out
Ok so I got to the PC (with no delay whatsoever) and I made a project with your config to test.
However, I need a bit more clarification. Do you want to get back an an array of users with the latest message they sent, or the latest message they received? Or the latest of both?
My bad actually, you stated clearly that you want the latest option
You should probably do that with
extras
and the magic sql
operator thingHmm, not f familiar with that one. I will check out the docs.
So, I tried doing this exact thing, but it always overcomplicates the solution so so much.
I think the best solution is probably just
And I defined my relations like so:
Then you just have latest of each, while obviously still only executing one query (db.query always sends one query only)
I tried doing something along the lines of
However, because messages in the user table are defined as only relating to the sender_id, this couldn't work.
I will look at it once I get a chance. Thank you!
I restructured my database a bit since it was a bitch to work with the way I wanted it to, but using relational queries I finally got it working. Thank you!