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.
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.
So here is another schema.I would describe a purpose as the following:
user_group_chat
, I make the columnuser_id
,group_id
andcreated_at
as a PRIMARY KEY. The columnuser_id
is also a FOREIGN KEY of tableusers
but on DELETE will be CASCADE, andgroup_id
is also a FOREIGN KEY of tablegroups
and on DELETE will be CASCADE too. And the reason for making those as FOREIGN KEY are simple. If a user or a group is not exists, they should be gone too.user_user_chat
, I make the columnfrom_user_id
,to_user_id
andcreated_at
as a PRIMARY KEY too. In a nutshell, it's behavior is the same as tableuser_group_chat
too. It's just this table is responsible for storing a chat between a user and a user.Consider storing one message per row in the table:
id, user1id, user2id, message, status, timestamp
where id is an autoincrement column.
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)
Here is one take on an ERD for your db.
5/6/2016 edit Adding DDL with (hopefully) improved field types and names
Why not have a table structure like this:
chats
chatContent
This way, your data is much easier to search and organize. For example, what if you wanted to get a certain message spoken at X time? or you want to get all chat messages with X status?
Seperating the data into 2 tables should be much nicer and neater.