-1

I am using a SQL table to store all my users along with their relevant information. Each user can sometimes have messages sent to them by another user, and I'm having trouble figuring out how to store these messages, and connecting them with the correct receiving user.

I've thought of making a new table called messages that contains all the messages of all the users, and each time a user logs in it will query and display all the messages pertaining to that user. However, I'm not sure if this is the best approach to this problem or whether it will get quite slow after thousands or hundreds of thousands of messages.

Is this method viable, or is there a better way to accomplish this?

4

1 回答 1

1

You have a 1-N relationship between users and messages, so I would recommend a separate table to store the messages, that would reference the id of the send and of the receiver through foreign key constraints.

The DDL would look like:

create table users (
    user_id int primary key auto_increment,
    name    varchar(50),
    ...
);

create table messages (
    message_id  int primary key auto_increment,
    sender_id   int references users(user_id),
    receiver_id int references users(user_id),
    title       varchar(200),
    content     varchar(1000),
    ...
);

Now say that you want to fetch the details of ead user and all messages that they recieved, you can join as follows:

select u.*, m.title, m.content, m.sender_id
from users u
inner join messages m on m.reciever_id = u.user_id

You can also get the information about the sender with another join on user, like so:

select u.*, m.title, m.content, s.name sender_name
from users u
inner join messages m on m.reciever_id = u.user_id
inner join users s on s.user_id = m.reciever_id
于 2020-10-17T22:45:12.100 回答