Sql join,2个表,相同的字段

时间:2010-06-05 20:29:04

标签: sql sql-server

我有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;

但这不起作用。我顺便使用Ms sql2000。

3 个答案:

答案 0 :(得分:9)

使用不同的别名加入用户表两次。首先加入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;

答案 1 :(得分:2)

您需要两次加入tabUsers。一个得到发件人,一个得到收件人:

SELECT m.*, f.userName as Sender, t.userName as Recipient 
FRPOM tabMessages AS m
    INNER JOIN tabUsers AS f on m.msgFrom = f.userId
    INNER JOIN tabUsers AS t on m.msgTo = t.userId 
WHERE m.msgId = @someParameter;

答案 2 :(得分:0)

您是否尝试过 UNION ??

http://www.w3schools.com/sql/sql_union.asp