[英]How to join two tables where one column in one table refers to 3 columns in other table?
[英]How can i join two tables with two columns that refers the same column in the second table in SQL Server
我有两张桌子要加入。
第一个表有两列
第二个表有 userId 和 username 列。 第一个表的这两列是指同一个表的同一列。 我想在一个视图中查看两个用户名,但我无法同时获得它们。 我该怎么做?
编辑
select
TASKID,
CREATED_BY,
CREATED_AT,
ASSIGNED_USER,
USERNAME ,
DEADLINE,
USERNAME
from
TASKS
inner join
USERS on ASSIGNED_USER = USERID
我可以通过上面的查询获得ASSIGNED_USER
的用户名的用户名。 我已经尝试了第二个来获取两个用户名,但它没有用
select
TASKID,
CREATED_BY,
CREATED_AT,
ASSIGNED_USER,
USERNAME ,
DEADLINE,
USERNAME
from
TASKS
inner join
USERS on ASSIGNED_USER = USERID and CREATED_BY = USERID
它返回一个空结果。
加入 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
您必须为 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.