views:

114

answers:

4
+1  A: 

How about User table, Messages table, Message sender table - contains mapping of sender userid and message id. A receiver message table with receipent user id and message id. So multiple receipents would be mapped to same message id but there will be multiple rows in the table. Makes sense ?

Prashant
+11  A: 

I can see no better solution than to dynamically create a table for each new user...

You should never see "dynamically created tables" from a relational-databases point of view.


In general your problem is solved as follows:

  • A users table with (user_id, name, surname ...)
  • A messages table with (message_id, time_stamp, subject, body, sent_by ...)
  • A messages_recipients table (message_id, recipient_id)

Both the sent_by field in the messages table and the recipient_id field in the messages_recipients tables should be foreign keys to the user_id field in the users table.

Daniel Vassallo
Ah yes, the messages_recipients table is the missing link. I will try to implement it (coming back to database programming after 5 years or so). Thanks!
Dabblernl
I find this answer very useful for db newbies. Any idea how to rephrase its title to make it more easily found?
Dabblernl
@Dabblernl: Maybe something like 'storing arrays in a database'? ... +1 for the effort to help newbies :)
Daniel Vassallo
+3  A: 

The "table per user"-idea is horror (sorry).

Prashant is right about the design, although I'd like to add a little improvement: since a msg will have one sender only, there is no need for a separate table to keep track of senders, but you could have a field "sender" in the messages-table. Plus the recipients-table to map msgs+recipients.

MBaas
Thanks, The very reason for asking the question was exactly that it didn't feel right to create tables on the fly.
Dabblernl
A: 

You are describing a many-to-many relationship, so what you need is a junction table that sits in-between the [Users] (recipients) and [Messages] tables.

For example, a table, [UserMessages], that holds it's own primary key id, as well as two further columns that represent a User PK, and Message PK.

Queries, entities etc. can then associate multiple messages with multiple users by joining across these tables.

Mezza