3

sorry if I'm not framing this question properly but I'm very new to SQL statements and I can't seem to get this right I need help working out how to do a SELECT statement with a lookup table involved, there's the situation:

Employee table
[ID], [Name], [StartDate]

User_Roles (lookup) table
[Employee_ID], [Role_ID]

Roles Table
[Id], [RoleName]

So, from what I can see the employee has an ID, Name, and StartDate,

the User_Roles table assigns a role ID to the user ID and

the Roles Table has the Roles Codes.

I needed a Select statement that returns:

Employee.ID, Employee.Name, Employee.StartDate, Roles.RoleName

Based on what the mapping is in the User_Roles table.

Many thanks in advance for your help

4

2 回答 2

6

您需要使用多个连接来处理关系。

select e.id, e.name, e.startDate, r.RoleName 
from employee e 
join user_roles ur
on e.id = ur.employee_id
join roles r
on r.id = ur.role_id

完整示例

/*DDL*/

create table EMPLOYEE(
   ID int,
   Name varchar(50),
   StartDate date
);

create table USER_ROLES(
  Employee_ID int,
  Role_ID int
);

create table Roles(
  ID int,
  RoleName varchar(50)
);

insert into EMPLOYEE values(1, 'Jon Skeet', '2013-03-04');
insert into USER_ROLES values (1,1);
insert into ROLES values(1, 'Superman');

/* Query */
select e.id, e.name, e.startDate, r.RoleName 
from employee e 
join user_roles ur
on e.id = ur.employee_id
join roles r
on r.id = ur.role_id;

工作示例

很好的文章解释连接

于 2013-06-04T09:30:35.583 回答
1

你可以这样做:

SELECT e.ID, e.Name, e.StartDate, r.RoleName
FROM Employee as e
INNER JOIN UserRoles as ur on ur.EmployeeID = e.ID 
INNER JOIN Roles as r on ur.Role_ID = r.Id

请注意,如果员工拥有多个角色,您将获得每位员工的多行数据。

于 2013-06-04T09:31:14.663 回答