The one method can be to separate the global messages from the personal messages as I think you have tried to do already.
To effectively get a read status for a global message, you would need to add a table with a composite key containing the global_message_id and user_id together.
messages_tbl
- message_id | int(11) | Primary Key / Auto_Increment
- message_type | int(11)
- sender_id | int(11) | FK to sender
- receiver_id | int(11) | FK to receiver
- status | int(1) | 0/1 for Unread / Read
- message | text
- date | datetime
global_message_tbl
- g_message_id | int(11) | Primary Key / Auto_Increment
- g_message_type | int(11)
- sender_id | int(11) | FK to sender
- date | datetime
global_readstatus_tbl
- user_id | int(11) | Primary Key
- g_message_id | int(11) | Primary Key
- date | datetime
Alternatively merge the messages_tbl
and global_message_tbl
so they each user is sent a global message personally in a loop. This reduces your schema right down to one table.
messages_tbl
- message_id | int(11) | Primary Key / Auto_Increment
- sender_id | int(11) | FK to sender
- receiver_id | int(11) | FK to receiver
- status | int(1) | 0/1 for Unread / Read
- message_type | varchar(8) | Personal / Global / Company
- message | text
- date | datetime
- type | varchar(8)
If you want the ability to normalise your table a bit better, and make it easier to add message types in the future, move message_type back into its own table again, and make message_type
a FK of the message_type_id
message_type_tbl
- message_type_id | int(11) | Primary Key / Auto_Increment
- message_type | varchar(8) | Personal / Global / Company
Update - Sample Table (1 Table)
message_tbl
message_id | message_type | sender_id | receiver_id | status | message | datetime
1 | personal | 2 | 3 | read | foobar | 12/04/11 00:09:00
2 | personal | 2 | 4 | unread | foobar | 12/04/11 00:09:00
3 | personal | 3 | 2 | unread | barfoo | 12/04/11 02:05:00
4 | global | 1 | 2 | unread | gmessage | 13/04/11 17:05:00
5 | global | 1 | 3 | unread | gmessage | 13/04/11 17:05:00
6 | global | 1 | 4 | read | gmessage | 13/04/11 17:05:00
user_tbl
user_id | name
1 | Admin
2 | johnsmith
3 | mjordan
4 | spippen
The above assumes users 2, 3 and 4 are general users sending messages to each other, user 1 is the admin account that will be used to send global messages (delivered directly to each user individually) allowing you to see the same information as if it were a personal message.
To send a global message in this format you would simply loop over the users table to obtain all the ID's you want to send the global message out to, then simply INSERT
the rows for each user in the messages_tbl
.
If you don't anticipate your users sending millions of messages a day as well as regular global messages to millions of users then the number of rows shouldn't be an issue. You can always purge old read messages from users by creating a cleanup script.