[英]MySQL query to display name from sender and receiver
I have a table called users
which looks like this: 我有一个称为
users
的表,看起来像这样:
+----+----------------+
| id | name |
+----+----------------+
| 1 | Blake |
| 2 | Jenn |
+----+----------------+
And i have a table called msg
which looks like this: 我有一个名为
msg
的表,看起来像这样:
+----+----------------+----------------+
| 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). 所以现在我有一个问题,因为我不知道如何将msg.sender(id)加入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. 只需将
users
表与msg
表join
两次-在发送者上然后在接收者上。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.