将聊天消息存储在 MySql 表中 [英] Storing chat messages inside a MySql table

查看:28
本文介绍了将聊天消息存储在 MySql 表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几周里,我一直在开发基于 Web 的聊天客户端应用程序,我有一个关于将聊天消息存储在 MySql 表中的问题.我创建了一个名为对话的表,现在它包含 5 个字段;

For the last couple of weeks I've been working on a web based chat client application and I have a question regarding storing chat messages inside a MySql table. I created a table called conversations and for now it consists of 5 fields;

user1ID, user2ID ,messages(mediumtext), status, timestamp.

user1ID, user2ID ,messages(mediumtext), status, timestamp.

当我测试聊天应用程序时,一切正常,但问题是每次用户发送内容时,我都会将该值作为新行附加到我的消息"字段中.当涉及到检索消息时,我的 sql 代码会读取整个内容并将其显示给相应的用户.因此,数据量随着添加到消息字段中的文本量而线性增加.我的问题是,有没有办法只从文本字段中选择最后一行,或者可能是另一种可以减少传输数据量的解决方案.

When I test the chat application everything works perfectly fine, but the problem is every time a user sends something, I'm appending that value into my 'messages' field as a new line. And when it comes to retrieving the message, my sql code reads the whole thing and show it to the corresponding user. So the amount of data linearly increase by the amount of text added into the messages field. My question is, is there any way to SELECT only the last line from a text field or maybe another solution that will reduce the amount of transferred data.

推荐答案

您需要更好的 db 架构 - 更具关系性.这样做还会为您带来其他一些改进(密码保护聊天和多用户聊天等等)

You need a better db schema - more relational. Doing so will give you some other improvements as well (password protected chats and multi-user chat to name a couple)

这是您的数据库的 ERD.

Here is one take on an ERD for your db.

5/6/2016 编辑添加具有(希望)改进的字段类型和名称的 DDL

5/6/2016 edit Adding DDL with (hopefully) improved field types and names

CREATE TABLE user
(
    user_id CHAR(32),
    user_login VARCHAR(255),
    user_password CHAR(64),
    user_email VARCHAR(400),
    PRIMARY KEY (user_id)
);

CREATE TABLE message
(
    message_id CHAR(32),
    message_datetime DATETIME,
    message_text TEXT,
    message_chat_id CHAR(32),
    message_user_id CHAR(32),
    PRIMARY KEY (message_id)
);

CREATE TABLE user_chat
(
    user_chat_chat_id CHAR(32),
    user_chat_user_id CHAR(32),
    PRIMARY KEY (user_chat_chat_id,user_chat_user_id)
);

CREATE TABLE chat
(
    chat_id CHAR(32),
    chat_topic VARCHAR(32),
    chat_password CHAR(64),
    user_chat_user_id CHAR(32),
    PRIMARY KEY (chat_id)
);

CREATE INDEX user_login_idx ON user (user_login);
ALTER TABLE message ADD FOREIGN KEY message_chat_id_idxfk (message_chat_id) REFERENCES chat (chat_id);

ALTER TABLE message ADD FOREIGN KEY message_user_id_idxfk (message_user_id) REFERENCES user (user_id);

ALTER TABLE user_chat ADD FOREIGN KEY user_chat_user_id_idxfk (user_chat_user_id) REFERENCES user (user_id);

ALTER TABLE chat ADD FOREIGN KEY chat_id_idxfk (chat_id,user_chat_user_id) REFERENCES user_chat (user_chat_chat_id,user_chat_user_id);

这篇关于将聊天消息存储在 MySql 表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆