贝利信息

如何设计高效的聊天表结构,才能轻松获取用户所有发送和接收的会话信息?

日期:2024-11-11 00:00 / 作者:霞舞

聊天表设计

在设计类似 csdn 私信系统的聊天表时,需要解决以下问题:

针对这些问题,现有表结构存在以下局限:

表a conversation
id send_user to_user
1 9 10
表b message
id conversation_id send_user message
1 1 9 你好
2 1 10 你好

获取会话列表

为了解决获取会话列表的问题,我们可以使用以下查询:

select * from conversation where to_user = b

该查询将返回用户 b 接收的所有私信会话。

获取所有发送会话和接收会话

要获取用户 b 所有发送和接收的会话,可以使用以下查询:

(select * from conversation where to_user = b)
union
(select * from  conversation where  send_user=b)

优化考虑

如果系统规模较大,上述查询可能会对数据库性能造成影响。优化方法包括: