简体   繁体   English

使用查找表时的SQL SELECT语句

[英]SQL SELECT statement when using look up table

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: 对不起,如果我没有正确构建这个问题,但我对SQL语句很新,我似乎无法做到这一点我需要帮助解决如何使用查找表执行SELECT语句,情况如下:

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, 所以,从我所看到的, employee有一个ID,名称和StartDate,

the User_Roles table assigns a role ID to the user ID and User_Roles表为用户ID分配角色ID

the Roles Table has the Roles Codes . Roles Table具有角色代码

I needed a Select statement that returns: 我需要一个返回的Select语句

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

Based on what the mapping is in the User_Roles table. 基于User_Roles表中的映射。

Many thanks in advance for your help 非常感谢您的帮助

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;

Working Example 工作实例

Nice Article Explaining Joins 好文章解释连接

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. 请注意,如果员工有多个角色,您将获得每位员工多行。

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

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