I am designing a message/comment table in MySQL for social networking site. I have a messaging system where participating two users (only two and not more than that) will have single/unique thread. So, whenever a user is messaging another user then it will check whether both user had unique thread IF NOT then it will create unique thread for both user.
create table comment_threads (
thread_id int (PK),
user_id_1 int,
user_id_2 int,
created datetime
);
create table comments (
comment_id int (PK),
thread_id int (FK),
comment text,
created datetime
);
Whenever a user messages another user each time then I have to che开发者_开发知识库ck whether both of the participating user had previous thread so i have to query the database for that (QUERY 1). And then again if there wasn't any thread to create a thread in comment_thread (QUERY 2). Then again to post comment in comment table (QUERY 3). So I have to query two or three times for messaging.
Questions:
- Is the above tables correct way of solving my problem or it needs some correction?
- Is there any other better way to do it?
You don't really need to have 2 tables.. 1 table should be fine:
create table comments (
comment_id int (PK),
parent_id int,
user_id_1 int,
user_id_2 int,
comment text,
created datetime
);
For a new thread, set the parent_id to 0. For future comments, you can set the parent_id to the ID of first comment.
This way, you can also do multi-level threaded conversations, and it makes it easy to do stuff like 'comments I've posted'.
As per Itay's answer, you should use some caching mechanisms to improve performance.
- You can't know which user left which message
- When you instantiate the message system with a thread, cache the two users ids and thread id, no need to run to DB for each submit (this is not that simple, but rather a direction for you, you will need some failsafes mechanisems)
- I would buffer in memory the thread and submit to DB only at a later time (or just use a memory table)
- since this is a two users only, one thread only system, you can de-normalize and do the entire thread in one record inside a huge text field where you concatenate the latest entry to the end. Again, this is just a direction and not the complete solution.
精彩评论