简体   繁体   English

INNER JOIN 两列合一

[英]INNER JOIN two columns to one

Here's what my 2 tables look like这是我的 2 个表的样子

Table A表A

userID | adminID

Table B表B

IDs | fName

In Table A, both the userID and adminID are found in table B. I'm trying to return the full name for each.在表 A 中, userIDadminID都在表 B 中找到。我试图返回每个的全名。

This is the SQL I am currently using这是我目前使用的SQL

SELECT fName
FROM tableB
INNER JOIN tableA ON tableA.userID = tableB.IDs. 

This is where I'm stuck.这就是我被困的地方。 This only returns 1 column.这只返回 1 列。 I would like it to return each fName in their own column.我希望它在各自的列中返回每个fName Any help is appreciated.任何帮助表示赞赏。 Thank you.谢谢你。

Or, if this is more of an employee and their admin point-of-contact and you want it on each row, such that different employees could have different admin contacts..或者,如果这是更多的员工和他们的管理员联系人,并且您希望它在每一行上,这样不同的员工可以有不同的管理员联系人。

select
      a.UserID,
      u.fname UserFirstName,
      au.fname AdminFirstName
   from
      tableA a
         join tableB u
            on a.userID = u.IDs
         join tableB au
            on a.adminID = au.IDs

Now, if the admin ID is not always available, just change the second join to a LEFT JOIN.现在,如果管理员 ID 并不总是可用,只需将第二个连接更改为 LEFT JOIN。 Notice different alias references of the same table to get context of each first name.注意同一个表的不同别名引用以获取每个名字的上下文。

Have you tried UNION ?你试过UNION吗?

SELECT fName FROM tableB INNER JOIN tableA ON tableA.userID=tableB.IDs
UNION
SELECT fName FROM tableB INNER JOIN tableA ON tableA.adminID=tableB.IDs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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