
聊天表设计
在设计类似 csdn 私信系统的聊天表时,需要解决以下问题:
- 如何获取接收私信方的会话列表?
- 如何让接收方获取该用户所有发送人和发送的会话信息?
针对这些问题,现有表结构存在以下局限:
表a conversation
| id | send_user | to_user |
|---|---|---|
| 1 | 9 | 10 |
| 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)
优化考虑
如果系统规模较大,上述查询可能会对数据库性能造成影响。优化方法包括:
- 使用索引来加快查询速度。
- 使用一个单一的表来存储会话和消息信息,而不是使用两个表。
- 考虑使用 redis 等缓存机制来降低数据库的负载。










