内表连接3表

时间:2014-09-24 11:03:41

标签: sql

在表格审批人中:

No Userid 
1   3
2   7

在表用户中:

No UserID RoleID
1  3        1
2  4        1
3  5        2
4  7        3

表角色

RoleID Name
1      ABC
2      BCD
3      CDE

我想在表格审批者中选择用户的角色名称,如:

Userid Name
3      ABC
7      CDE

4 个答案:

答案 0 :(得分:1)

select 
  a.Userid,
  r.Name
from 
  Approver a
  join Users u on a.no = u.no
  join Roles r on u.RoleID = r.RoleID

答案 1 :(得分:1)

我不是百分之百确定为什么approver.no在用户和审批者表上....我将假设userId在这两种情况下都是唯一的......如果是这样的情况应该有效:

select 
    u.userid, 
    r.name
from
    Approver as a
    inner join [Users] as u on a.userId = u.UserId
    inner join [Roles] as r on u.roleId = r.roleId

如果不是这种情况,并且您需要approver.no user.UserId组合是唯一的,则以下内容应该有效:

select 
    u.userid, 
    r.name
from
    Approver as a
    inner join [Users] as u on a.userId = u.UserId
    and a.No = u.No
    inner join [Roles] as r on u.roleId = r.roleId

就结果集问题而言,这两者之间的差异可以在这里找到:http://sqlfiddle.com/#!3/0daa9/4

请注意,第二个查询针对提供的数据返回单个结果

答案 2 :(得分:0)

SELECT U.UserID,
       Name
FROM   Approver A
       JOIN Users U
           ON A.UserId = U.UserId
       JOIN Roles R
           ON R.RoleId = U.RoleId

<强> SQL FIDDLE DEMO

答案 3 :(得分:0)

 SELECT Approver.UserId, Name from Approver INNER JOIN Users
 on Approver.No=Users.No
    INNER JOIN Roles
 on Users.RoleID=Roles.RoleID