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 check 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:
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.