postgresql 如何向查询中添加子查询?

qij5mzcb  于 2023-03-08  发布在  PostgreSQL
关注(0)|答案(2)|浏览(150)

如何向查询添加子查询以显示会议室中的最后一条消息?
聊天室

id, type(USER_TO_USER, USER_TO_SHOP, USER_TO_PLATFORM), name

信息列表

room_messages - id, participant_id, text, is_read

我的查询

select r.id, r.name from rooms as r
left join room_participants rp on r.id = rp.room_id
where rp."participantType" = 'USER' and rp.participant_id = 1
2nbm6dog

2nbm6dog1#

你需要先得到每个房间的最后一条消息,然后加入其余的表:

SELECT r.id
      ,r.type
      ,r.name
      ,rm.text
FROM rooms r
INNER JOIN 
(
      SELECT participant_id, MAX(id) AS max_id
      FROM room_messages 
      GROUP BY participant_id
) rm_max 
    ON rm.id = rm_max.participant_id 
INNER JOIN room_messages rm
    ON r.id = rm.participant_id
    AND rm_max.max_id = rm.id
ORDER BY rm.chat_room_id;
4nkexdtk

4nkexdtk2#

稍微调整了一下

SELECT r.id
      ,r.type
      ,r.name
      ,rm.text
      ,rmf.file
FROM rooms r
LEFT JOIN room_participants rp
    on r.id = rp.room_id
INNER JOIN
(
      SELECT room_id, MAX(id) AS max_id
      FROM room_messages
      GROUP BY room_id
) rm_max
    ON r.id = rm_max.room_id
INNER JOIN room_messages rm
    ON r.id = rm.room_id AND rm_max.max_id = rm.id
LEFT JOIN room_message_files rmf
    ON rm.id = rmf.room_message_id
where rp."participantType" = 'USER' and rp.participant_id = 1
ORDER BY rm.room_id;

相关问题