我有一个消息传递应用程序,我需要在其中返回用户所属的所有对话以及与每个对话相关联的消息。我想限制每个对话的消息数。
表结构如下:
用户
| id | name | email | created_at |
|------|------|----------|------------|
| 1 | Bob | [email protected] | timestamp |
| 2 | Tom | [email protected] | timestamp |
| 3 | Mary | [email protected] | 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()
,但不确定如何实现它们/如果需要它们的话。
这是使用100 users
限制每个row_number()
对话的示例。以descending
的顺序获取最新的conversations
。
select * from
messages t1
inner join(
select row_number() over (partition by user_id order by conversation_id desc) rn, conversation_id, user_id
from conversations_users) t2 on t1.user_id = t2.user_id
where rn <= 100
order by created_at asc;
您确实可以使用row_number()
。以下查询将为您提供给定用户每次会话的最后10条消息:
select *
from (
select
m.*,
row_number() over(
partition by cu.user_id, m.conversation_id
order by m.created_at desc
) rn
from messages m
inner join conversations_users cu
on cu.conversation_id = m.conversation_id
and cu.user_id = 1
) t
where rn <= 10
order by conversation_id, created_at desc
注意:
我将带有in
的子查询转换为常规的join
,因为我认为这是表达您要求的一种更整洁的方式
我在分区子句中添加了用户ID;因此,如果删除对用户进行过滤的where
子句,则将获得每个用户对话的10条最后一条消息]]
您可以使用ROW_NUMBER()
限制每个对话中的消息。获取最新的: