网站首页mysql

分享一个群发公告、消息功能的实现

发布时间:2016-08-18 06:32:32编辑:阅读(4308)

    已知系统中有一个用户表及其对应的用户组, 需求为:可群发公告给所有人,或者针对某些个用户组或者某些个用户发消息。



    一、设计数据表

    消息表

    【message】主要字段
    id         int             ID
    title      varchar(255)    标题
    content    text            内容
    addtime    int             发布时间戳
    groups     varchar(2000)   接收的用户组列表,以逗号,间隔
    members    varchar(2000)   接收的用户列表,以逗号,间隔

    公告接收表:

    【message_receive】主要字段
    id            int    ID
    message_id    int    消息ID
    members_id    int    接收者ID
    status        int    删除标志


    二、在群发消息时,只在【message】表中添加一条记录。


    三、用户登陆时,自动检测【message】表中有无未读消息,有则提示用户查阅消息。

    SQL如下:  $groupId为当前登陆用户的分组ID,$membersId为当前登陆用户的ID。

    SELECT * FROM {message} a 
    WHERE 
        (    
            find_in_set(a.groups, '{$groupId}') 
            or  
            find_in_set(a.members, '{$membersId}')
        )
        AND 
            a.id NOT IN 
        (
            select b.announce_id 
            from 
                {message_receive} b 
            where 
                members_id='{$membersId}'
        )


    四、用户查看消息时,在【message_receive】表中添加一条该用户查看此消息的记录。


    五、在用户打开已读消息时,只需要从【message_receive】表中查询对应记录。

    SQL如下:  $groupId为当前登陆用户的分组ID,$membersId为当前登陆用户的ID。

    SELECT * FROM {message} a 
    WHERE 
            (
                    find_in_set(a.groupid, '{$groupId}') 
                    or  
                    find_in_set(a.members_id, '{$user_id}')
            ) 
            AND
                     a.id IN 
            (
                    select b.announce_id 
                    from 
                        {gonggao_receive} b 
                    where 
                        b.members_id='{$membersId}' 
                        and 
                        b.status=1
            )


    六、删除已读消息时,更改【message_receive】表的status状态值。




    此方法只在用户登陆时,主动查收消息,当系统中有大量用户时则优势尽显,节省大量空间, 时间上的损耗也并不明显。




评论

  • 昵称:wi jf h 来自:222.137.235.247发表于:2019-11-07 06:27:24
    楼主牛*