我有一个消息传递应用程序,需要返回用户所属的所有对话以及与每个对话相关联的消息。我想限制每次对话的消息数。
表结构如下:
用户
| id | name | email | created_at |
|------|------|----------|------------|
| 1 | Bob | a@b.com | timestamp |
| 2 | Tom | b@b.com | timestamp |
| 3 | Mary | c@b.com | timestamp |
消息
| id | sender_id | conversation_id | message | created_at |
|------|-----------|------------------|---------|------------|
| 1 | 1 | 1 | text | timestamp |
| 2 | 2 | 2 | text | timestamp |
| 3 | 2 | 1 | text | timestamp |
| 4 | 3 | 3 | text | timestamp |
对话
| id | created_at |
|----|------------|
| 1 | timestamp |
| 2 | timestamp |
| 3 | timestamp |
Conversations_Users
| id | user_id | conversation_id |
|----|---------|-----------------|
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 2 | 2 |
| 3 | 3 | 2 |
| 4 | 3 | 3 |
| 5 | 1 | 3 |
我想加载用户(id 1)所在的所有对话(在示例中-对话1和3)。对于每个对话,我需要与之关联的消息,按conversation_id
分组,按created_at ASC
排序。我当前的查询处理此问题:
SELECT
*
FROM
messages
WHERE
conversation_id IN (
SELECT
conversation_id
FROM
conversations_users
WHERE
user_id = 1
)
ORDER BY
conversation_id,created_at ASC;
但是,这会将大量数据粘贴到内存中。因此,我想限制每次对话的消息数量。
我看过rank()
和ROW_NUMber()
,但不确定如何实现它们/如果需要它们。