設計優點,發系統消息給全站使用者隻需一條記錄,不需要每個使用者都插入,解決使用者量大的問題
登入使用者隻顯示未讀的消息。使用者檢視未讀消息後,将消息插入消息資源回收筒表标記為已讀,uid與該使用者綁定,是以資源回收筒表沒有uid=system的記錄。
2)已讀消息清單:實作方法有2種取其一即可
2.1)插入消息資源回收筒表并删除使用者的未讀消息表對應記錄(非system)
2.2)插入消息資源回收筒表
删除的消息清單:隻插入消息資源回收筒表,
未讀消息:目前使用者沒有讀過的消息
未讀消息/消息表

drop table if exists `msg`;
create table `msg` (
`id` int(11) unsigned not null auto_increment,
`mail` varchar(60) not null default 'system' comment '郵箱:預設為system表示發給所有使用者',
`title` varchar(50) default null comment '标題',
`content` text not null comment '内容',
`createtime` int(10) unsigned not null default '0' comment '建立時間',
primary key (`id`)
) engine=myisam auto_increment=14 default charset=utf8 comment='公告表';
insert into `msg` values (1,'system','系統公告','今天天氣不錯',1394421260);
insert into `msg` values (2,'[email protected]','使用者i','aaaaaaaaaaaa',1394421299);
insert into `msg` values (3,'[email protected]','使用者公告heihei','aaaaaaa',1394421299);
insert into `msg` values (4,'system','系統公告2','第二條消息',1394421260);
已讀消息或删除消息

drop table if exists `msgrecycle`;
create table `msgrecycle` (
`id` int(11) not null auto_increment,
`uid` varchar(200) not null comment '使用者id',
`msgid` int(11) not null comment '消息id',
`isread` int(1) unsigned not null default '0' comment '0-未讀 1-已讀',
`isdelete` tinyint(1) not null default '0' comment '0-未删除 1-删除',
) engine=myisam auto_increment=8 default charset=utf8;
lock tables `msgrecycle` write;
insert into `msgrecycle` values (1,'[email protected]',2,1,0);
insert into `msgrecycle` values (2,'[email protected]',3,0,1);//删除的未讀消息
insert into `msgrecycle` values (3,'[email protected]', 1, 1, 0); //[email protected]使用者已讀的system消息
unlock tables;
顯示使用者已讀消息mr.uid='[email protected]'
2.2)

select * from msg m left join msgrecycle mr on m.id=mr.msgid where (m.mail='system' or m.mail='[email protected]') and mr.uid='[email protected]' and isread=1 and isdelete=0
2.1)

select * from msgrecycle where uid='[email protected]' and isread=1 and isdelete=0
顯示使用者未讀消息 = 消息資源回收筒表沒有讀過的使用者消息記錄+消息資源回收筒表沒有讀過的系統消息記錄
消息資源回收筒表沒有讀過的使用者消息記錄

select m.* from msg m left join msgrecycle mr on m.id=mr.msgid where m.mail='[email protected]' and mr.id is null
消息資源回收筒表沒有讀過的系統消息記錄

select * from msg where mail='system' and id not in (select m.id from msg m left join msgrecycle mr on m.id=mr.msgid where m.mail='system' and mr.uid='[email protected]' and isread=1 and isdelete=0)