How to store arrays in a database?
I have a simple messaging system that up till now uses file based storage. Because the number of users of the system is increasing gradually I would like to switch over to database based storage.
In code the message server maintains a list of users (with their credentials) and a list of messages. A Message object has as its main fields a Sender (of type User), Recipients (of type User[]) and a Content(of type string).
Typically, a user will request the messages addressed to him from the server and receive all messages in which the Recipients field contains his own username.So, for the database I envision the following tables:
-A Users table -A Messages table (- a table for each user that specifies the messages addressed to him by MessageID)?The problem I have is how to store the Recipients field (which contains an array) in such a way that a database query can search it for the user tha开发者_如何学JAVAt requests to receive the messages addressed to him. I can see no better solution than to dynamically create a table for each new user that registers on the system that holds references to the messages in which he is listed as a recipient. Are other approaches possible?
Thanks a lot!
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.
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.
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 ?
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.
精彩评论