How to join only one row in joined table with postgres?

后端 未结 7 514
清歌不尽
清歌不尽 2021-01-31 01:31

I have the following schema:

CREATE TABLE author (
    id   integer
  , name varchar(255)
);
CREATE TABLE book (
    id        integer
  , author_id integer
  ,          


        
7条回答
  •  佛祖请我去吃肉
    2021-01-31 02:18

    I've done something similar for a chat system, where room holds the metadata and list contains the messages. I ended up using the Postgresql LATERAL JOIN which worked like a charm.

    SELECT MR.id AS room_id, MR.created_at AS room_created, 
        lastmess.content as lastmessage_content, lastmess.datetime as lastmessage_when
    FROM message.room MR
        LEFT JOIN LATERAL (
            SELECT content, datetime
            FROM message.list
            WHERE room_id = MR.id
            ORDER BY datetime DESC 
            LIMIT 1) lastmess ON true
    ORDER BY lastmessage_when DESC NULLS LAST, MR.created_at DESC
    

    For more info see https://heap.io/blog/engineering/postgresqls-powerful-new-join-type-lateral

提交回复
热议问题