我有2张表。为了简化:
表1,用户:
userId int,userName nvarchar(50)
表2消息:
msgId int,msgFrom int,msgTo int …
msg1和msg2都包含userId。现在,我想获取所有消息,但是我想要用户名而不是msgFrom。我知道该怎么办:
select tabMessages.*, tabUsers.userName as Sender from tabMessages inner join tabUsers on msgFrom=userId where msgId = @someParameter;
一切正常,花花公子。获取用户名而不是msgTo的方法相同。现在的问题是,如何在同一调用中同时获取两个字段?我想得到桌子
msgId,msgFrom,msgTo,发件人,收件人。我尝试过:
select tabMessages.*, tabUsers.userName as Sender, tabUsers.userName as Recipient from tabMessages inner join tabUsers on msgFrom=userId and msgTo=userId where msgId = @someParameter;
但这是行不通的。我正在使用sql2000女士。
使用不同的别名两次联接用户表。首先连接到from列,然后连接到to列。
from
to
select m.*, u1.userName as Sender, u2.userName as Recipient from tabMessages as m inner join tabUsers as u1 on u1.userId=m.msgFrom inner join tabUsers as u2 on u2.userId=m.msgTo where m.msgId = @someParameter;