Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL join to most recent record between tables

I have two tables pertaining to this question: conversations has many messages. The basic structure (with just the relevant columns) is as follows:

conversations (
  int id (PK)
)

create table conversation_participants (
  int id (PK),
  int conversation_id (FK conversations),
  int user_id (FK users),
  unique key on [conversation_id, profile_id]
)

create table messages (
  int id (PK),
  int conversation_id (FK conversations),
  int sender_id (FK users),
  int recipient_id (FK users),
  text body
)

For each conversations entry, given a user_id I want to receive:

  • all conversations that user participated in (i.e.: conversations.*)
  • joined to the most recent matching message (i.e.: order by messages.id desc limit 1)
  • conversations ordered by their most recent message id (i.e.: order by messages.id desc)

Unfortunately, all the query help I can seem to find on anything like this pertains to MySQL, and that doesn't work in PostgreSQL. The closest thing I found is this answer on StackOverflow that gives an example of the select distinct on (...) syntax. However, unless I'm just doing it wrong, I can't seem to get the results ordered in the correct way given the grouping constraints I need with that method.

like image 941
Matt Huggins Avatar asked Sep 02 '26 08:09

Matt Huggins


1 Answers

All information is in the table "messages", you don't need the other tables:

SELECT 
    id, 
    body,
    c.* -- content from conversations 
FROM messages 
    JOIN
        (SELECT MAX(id) AS id, conversation_id 
        FROM messages 
        WHERE 1 IN(sender_id, recipient_id) -- the number is the userid, should be dynamic
        GROUP BY conversation_id) sub
        USING(id, conversation_id)
    JOIN conversations c ON c.id = messages.conversation_id
ORDER BY
    id DESC;

Edit: Just JOIN on "conversations" to get the data needed from this table.

like image 82
Frank Heikens Avatar answered Sep 03 '26 23:09

Frank Heikens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!