简体   繁体   中英

How can i join two tables with two columns that refers the same column in the second table in SQL Server

I have two tables to join.

First table has two columns

  1. User ID of the record owner.
  2. User ID of the assigned user.

And the second table has userId and username columns. These two columns of first table refers to the same column of the same table. I want to see both user names in a view but I can't get those at the same time. How should I do that?

Edit

select
    TASKID,
    CREATED_BY,
    CREATED_AT,
    ASSIGNED_USER,
    USERNAME ,
    DEADLINE,
    USERNAME
from 
    TASKS
inner join 
    USERS on ASSIGNED_USER = USERID

I can get username of ASSIGNED_USER 's username with the query above. I've tried the second for getting both usernames but it didn't work

select
    TASKID,
    CREATED_BY,
    CREATED_AT,
    ASSIGNED_USER,
    USERNAME ,
    DEADLINE,
    USERNAME
from 
    TASKS
inner join 
    USERS on ASSIGNED_USER = USERID and CREATED_BY = USERID

It returns an empty result.

Join USERS twice to decode different references

select TASKID, CREATED_BY, CREATED_AT, ASSIGNED_USER, au.USERNAME assignedUser_Name, DEADLINE,  uc.USERNAME createdByUser_Name
from TASKS t
inner join USERS au
on t.ASSIGNED_USER = au.USERID 
inner join USERS uc
on t.CREATED_BY = uc.USERID

you have to join to user twice once for CREATED_BY and once for ASSIGNED_USER:

select
    TASKID,
    CREATED_BY,
    CREATED_AT,
    ASSIGNED_USER,
    USERNAME ,
    DEADLINE,
    USERNAME
from TASKS
inner join USERS u1 on ASSIGNED_USER = u1.USERID 
inner join USERS u2 on CREATED_BY = u2.USERID

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM