[英]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第一个表有两列
And the second table has userId and username columns.第二个表有 userId 和 username 列。 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.我可以通过上面的查询获得ASSIGNED_USER
的用户名的用户名。 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加入 USERS 两次以解码不同的引用
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:您必须为 CREATED_BY 和一次 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.