用MySQL实现用户消息通知系统,核心在于合理设计通知数据表,并通过读写分离与索引优化支撑高并发的未读查询与推送写入。下面直接看一种可落地的设计方案。

一、核心表结构设计
通常将通知分为全局通知与私信通知,可采用两张表:通知主表存放内容,用户通知关系表记录接收状态。
1. 通知主表 notification
CREATE TABLE notification ( id BIGINT PRIMARY KEY AUTO_INCREMENT, type VARCHAR(20) NOT NULL COMMENT '通知类型:system, comment, like', title VARCHAR(100) NOT NULL, content TEXT, sender_id BIGINT DEFAULT 0 COMMENT '发送者用户ID,0为系统', created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
2. 用户通知关系表 user_notification
CREATE TABLE user_notification ( id BIGINT PRIMARY KEY AUTO_INCREMENT, user_id BIGINT NOT NULL, notification_id BIGINT NOT NULL, is_read TINYINT NOT NULL DEFAULT 0 COMMENT '0未读 1已读', created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, INDEX idx_user_read (user_id, is_read), INDEX idx_notification (notification_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
二、推送通知的写入逻辑
当发生系统公告时,先插主表,再批量插关系表。若是单用户私信,仅插该用户的关系记录。
// 伪代码:向全量用户推送系统通知
function push_system_notification($title, $content) {
$nid = db_insert('notification', [
'type' => 'system',
'title' => $title,
'content' => $content,
'sender_id' => 0
]);
$user_ids = db_query('SELECT id FROM user WHERE status=1');
$batch = [];
foreach ($user_ids as $uid) {
$batch[] = ['user_id' => $uid, 'notification_id' => $nid];
}
db_batch_insert('user_notification', $batch);
}
三、用户拉取与未读统计
前端轮询或进入页面时调用接口,用以下SQL获取未读数与列表。
查询未读数量
SELECT COUNT(*) AS unread_count FROM user_notification WHERE user_id = 123 AND is_read = 0;
分页拉取通知列表
SELECT n.id, n.type, n.title, n.content, n.created_at, un.is_read FROM user_notification un JOIN notification n ON un.notification_id = n.id WHERE un.user_id = 123 ORDER BY un.created_at DESC LIMIT 0, 20;
四、标记已读与清理
用户点击通知后,更新关系表状态;历史通知可定时归档到备份表,保证主表体积可控。
UPDATE user_notification SET is_read = 1 WHERE user_id = 123 AND notification_id = 456;
五、设计注意点
- 关系表数据增长快,需按用户ID或时间做分表。
- 写主表与关系表要放在事务中,防止通知丢失。
- 高频未读查询依赖
idx_user_read索引,不要遗漏。 - 若推送量极大,可先写MQ由消费者落库,降低接口耗时。
MySQL方案适合日活百万内的产品,超出后可结合Redis缓存未读数,数据库仍作为可靠存储。