Sql 如何限制内部查询中特定列值的返回记录数?

Sql 如何限制内部查询中特定列值的返回记录数?,sql,postgresql,inner-join,Sql,Postgresql,Inner Join,我正在查询postgres数据库,以获取每个对话用户参与的5条消息 这是一个问题 select conversation.id, message from conversation inner join (select conversation.id as conversationId, conversation_reply.message from conversation_reply inner join conversation on conversation.id = con

我正在查询postgres数据库,以获取每个对话用户参与的5条消息 这是一个问题

select conversation.id, message from conversation inner join
(select conversation.id as conversationId, conversation_reply.message 
  from conversation_reply
  inner join  conversation on conversation.id = conversation_reply.c_id
  where conversation.user_one=22 or conversation.user_two=22 order by 
conversation_reply.time DESC limit 5) as messages on 
messages.conversationid = conversation.id
这将产生以下结果

80  jay%3A%20hello
80  jay%3A%20hey
80  jay%3A%20do%20this%20too
80  jay%3A%20throw%20please
80  jay%3A%20should%20be%20thrown
这些都是id为22的对话用户的所有消息,现在我只想限制每个对话的5条消息,以便

80 80msg1
80 80msg2
80 80msg3
80 80msg4
80 80msg5
73 73msg1
73 73msg2
73 73msg3
73 73msg4
73 73msg5
72 72msg1
72 72msg2
72 72msg3
这样的话,22号用户的每次对话我最多只有5条消息,我怎么能做到呢?限制是如何在内部查询中工作的?

我可以尝试使用带有窗口功能的ROW_NUMBER来生成rowNumber而不是limit


我认为横向连接是解决此问题的最佳方法:

SELECT c.id as conversationId,
       cr.message 
FROM conversation AS c
   CROSS JOIN LATERAL
      (SELECT message
       FROM conversation_reply
       WHERE c.id = conversation_reply.c_id
       ORDER BY conversation_reply.time DESC
       LIMIT 5) AS cr
WHERE c.user_one = 22
   OR c.user_two = 22;

使用横向连接,您可以使用连接右侧对话中的属性。

您可以提供表格中的一些示例数据吗?是的,当然可以,我应该发布屏幕截图吗?请不要发布屏幕截图。理想情况下,表是用CREATE语句和INSERT语句以及一些示例数据来描述的。您可以发布格式数据,而不是屏幕截图Thankshot这确实可以稍微更改,但由于消息表在内部查询中定义之前无法识别,所以@Laurenz Albe提到的横向连接处理得很好,谢谢,我会投票赞成:但是当使用除crossjoin之外的任何其他连接时,它会报告预期的内部、完整、右、左、交叉,但到达了哪里。然后可能是语法错误。我在这里使用交叉联接,因为您希望所有5条记录都与每个匹配行联接。
SELECT c.id as conversationId,
       cr.message 
FROM conversation AS c
   CROSS JOIN LATERAL
      (SELECT message
       FROM conversation_reply
       WHERE c.id = conversation_reply.c_id
       ORDER BY conversation_reply.time DESC
       LIMIT 5) AS cr
WHERE c.user_one = 22
   OR c.user_two = 22;