带有2个表的MySQL查询加入

I have a users like this:

id    username
1       user1
2       user2
3       user3

and a msgs like this:

t_id   sent_by   id    msg
1        2        1     whatever
2        3        1     is
3        2        1     here

Where users.id is a primary key and msgs.id is a foreign key. In the msgs table, id is the destination of the message sent by sent_by.

I want to select and display the username of sent_by as long as the logged in user (via sessions) is the msgs.id.

To clarify things, here is the pseudocode of what I wanted to do:

  1. Users has logged in. Store its userid to session.
  2. Display the distinct usernames of who sent me (the logged in user) the messages. In the example above, the display will be: user2, user3 if I have a user id of 1.

I was thinking of using join but ended up doing 2 queries for the sent_by and ids. It seems not an efficient query.

What should I do?

This is a straightforward JOIN since you only wish to return usernames of the sent_by ids.

$sql = "SELECT DISTINCT
    users.username
    msgs.sent_by
  FROM users JOIN msgs ON users.id = msgs.sent_by 
  WHERE id = {$_SESSION['my_userid']}";
SELECT DISTINCT u.username, m.sent_by
FROM msgs m
INNER JOIN users u ON u.id = m.sent_by
WHERE m.id = {$_SESSION['userid']}
ORDER BY m.t_id DESC