Sql join, 2 tables, same fields

前端 未结 3 703
你的背包
你的背包 2021-01-24 18:06

I have 2 tables. To simplify:

Table 1, users:


userId int, userName nvarchar(50)


Table 2 , messages:


msgId int, msgFrom int,

相关标签:
3条回答
  • 2021-01-24 18:26

    Join users table twice with different aliases. First join to from column, second to to column.

    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;
    
    0 讨论(0)
  • 2021-01-24 18:31

    You need to join onto tabUsers twice. One to get the sender, one to get the recipient:

    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;
    
    0 讨论(0)
  • 2021-01-24 18:34

    Did you try a UNION??

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

    0 讨论(0)
提交回复
热议问题