1. 程式人生 > >站內信設計(群發+私信)實踐

站內信設計(群發+私信)實踐

一:資料庫設計

DROP TABLE IF EXISTS message_read;
CREATE TABLE message_read (
id int(11) NOT NULL AUTO_INCREMENT,
wxAccountId int(11) DEFAULT NULL COMMENT ‘公眾號id’,
messageId int(11) DEFAULT NULL COMMENT ‘訊息id’,
delete_flag int(11) DEFAULT NULL COMMENT ‘刪除標誌:0未刪除 1:已刪除’,
PRIMARY KEY (id),
KEY wxAccountId

(wxAccountId),
KEY messageId (messageId)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS message_text;
CREATE TABLE message_text (
id int(11) NOT NULL AUTO_INCREMENT,
title varchar(50) DEFAULT NULL COMMENT ‘標題’,
content varchar(1024) DEFAULT NULL COMMENT ‘內容’,
created_at datetime DEFAULT NULL COMMENT ‘建立時間’,
status

int(11) DEFAULT ‘0’ COMMENT ‘0:未傳送 1:已傳送 ‘,
type int(1) DEFAULT ‘0’ COMMENT ‘0/全域性1/私有’,
from_id int(11) DEFAULT NULL COMMENT ‘傳送者account_id’,
to_id int(11) DEFAULT NULL COMMENT ‘接收者account_id’,
PRIMARY KEY (id),
KEY from_id (from_id),
KEY to_id (to_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

二:查詢已讀和未讀的列表
SELECT *,(
SELECT count(*)
FROM message_read
WHERE t.id = message_read.messageId
AND message_read.wxAccountId = #wxAccountId#
) AS readStatus
FROM message_text t
where t.id not in(select messageId from message_read where wxAccountId=#wxAccountId# and delete_flag=1) and t.status = 1 and t.type = 0 or t.to_id = #wxAccountId#
order by readStatus asc

三:查詢未讀的郵件數目

select count(*) from message_text t where t.id not in(select messageId from message_read where wxAccountId = #wxAccountId#) and t.status = 1 and (t.to_id = #wxAccountId# or t.type = 0)​

當閱讀【未讀】的站內信時,在message_read中插入一條閱讀記錄
當刪除【已讀】的站內信時,將message_read的delete_flag置為1