My question is more general than the example, but I think the only way to illustrate the idea is with a sample.
Let’s say I want to create a database for a chat application. There will be a list of topics. Any “room” 4 users at any one time.
Say there’s a topic called “beethoven”. If a user selects that topic, a room is fetched or created. Once 4 users have joined that room, another instance of the room is created (same topic), which will take up to 4 more users before another instance is created. If a user from the first room instance leaves, that slot is open, so the 9th user to join the topic will be sent to the first room instance.
What’s the best way to manage this? I have 2 ideas:
- “Topic” table: id, label
- “Rooms” table: id, topicId
- “Population” table: roomId, userId
When a user selects/joins a topic, something like SELECT COUNT(userId) FROM Population WHERE topicId = <id>… if count > 4, create a new Room, insert it and return the insert id. When a user leaves a room, that row in Population is deleted.
Or…
- “Topic” table: id, label
- “Rooms” table: id, topicId, user1, user2, user3, user4.
Then when a user joins, something like SELECT id FROM Rooms WHERE ISNULL(user1) OR ISNULL(user2) OR ISNULL(user3) OR ISNULL(user4) LIMIT 1
If there’s no matching rows, insert a new Room and return the insert id. When a user leaves a room, that column is set to NULL.
TYIA.
I used your first schema.
Get a list of non-full rooms:
Get the first non-full room id or NULL if no such room was found: