I am trying to create a facebook-style messaging system, where two or more users can have a conversation. In this messaging system, a user should be able to leave the conversation, without deleting it for the other participants.
In order to do this, i have made a set of tables like so:
User-table
+---------+----------+
| user_id | username |
+---------+----------+
| 1 | john |
| 2 | marc |
| 3 | vince |
+---------+----------+
Conversation-table
+-----------------+-------------------+---------------+
| conversation_id | newest_message_id | message_count |
+-----------------+-------------------+---------------+
| 1 | 7 | 7 |
| 2 | 13 | 6 |
| 3 | 56 | 43 |
+-----------------+-------------------+---------------+
Message-table
+------------+---------+---------------------------------+
| message_id | user_id | message |
+------------+---------+---------------------------------+
| 1 | 3 | "Yea, i really like him a lot." |
| 2 | 5 | "Let's meet up later!" |
| 3 | 13 | "Wow, thanks!" |
+------------+---------+---------------------------------+
Conversation_users-table
+----+-----------------+---------+
| id | conversation_id | user_id |
+----+-----------------+---------+
| 1 | 1 | 3 |
| 2 | 1 | 1 |
| 3 | 1 | 2 |
| 4 | 2 | 5 |
| 5 | 3 | 13 |
+----+-----------------+---------+
In my interface, i wish to display all the conversations in which a user is currently participating, along with the usernames of the other participants.
In order to do this i would have to get all the conversation-id's from the conversation_user-table in which the user is participating, and then go through the table again to get the user-id's of all the other participants of these conversations.
It works fine with a subquery like this:
SELECT user_id, conversation_id FROM conversation_users WHERE conversation_id IN (SELECT conversation_id FROM conversation_users WHERE user_id = 1)
but i am afraid that the nested query would decrease performance considerably.
Is there a better way to do this query?
Regards
SELECT user_id, conversation_id FROM conversation_users WHERE user_id = 1
are the same