Reputation: 636
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
Upvotes: 3
Views: 22990
Reputation: 94499
You need to use multiple joins to work across the relationships.
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
Full Example
/*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;
Upvotes: 6
Reputation: 121057
You can do it like this:
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
Please note that you will get several rows per employee if the employee has more than one role.
Upvotes: 1