I have a table called users
which looks like this:
+----+----------------+
| id | name |
+----+----------------+
| 1 | Blake |
| 2 | Jenn |
+----+----------------+
And i have a table called msg
which looks like this:
+----+----------------+----------------+
| id | sender | receiver |
+----+----------------+----------------+
| 1 | 1 | 2 |
| 2 | 2 | 1 |
+----+----------------+----------------+
So now i have a problem because i can't figure out how to join msg.sender(id) to users.name(name).
So basicly what i want to end up with, looks kind of like this:
+----+----------------+----------------+----------------+----------------+
| id | sender | sender_name | receiver | receiver_name |
+----+----------------+----------------+----------------+----------------+
| 1 | 1 | Blake | 2 | Jenn |
| 2 | 2 | Jenn | 1 | Blake |
+----+----------------+----------------+----------------+----------------+
I hope these illustrations kind of help with what I'm trying to explain.
Just join
the users
table twice with msg
table - Once on sender and then on receiver.
select m.*,
s.name as sender_name,
r.name as receiver_name
from msg m
join users s on m.sender = s.id
join users r on m.receiver = r.id;
You should join the user table twice using alias
select msg.sender, u1.name as sender_name, msg.receiver, u2.name as receiver_name
from msg
inner join users u1 on u1.id = msg.sender
inner join users u2 on u2.id = msg.receiver
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.