我是SQL的新手,我看起来似乎是一个非常简单的任务,但我似乎无法得到我知道应该得到的结果。
我有三张表,EMPLOYEE,SERVICE和PROPERTY。
我需要运行一个查询,在该查询中,它从EMPLOYEE返回已在波士顿的PROPERTY上处理过SERVICE工作的员工的名字和姓氏。
EMPLOYEE: EmployeeID, LastName, FirstName
SERVICE: EmployeeID, PropertyID
PROPERTY: PropertyID, City
这是我到目前为止所拥有的。我认为它做了我需要的但它看起来不对。
SELECT EMPLOYEE.LastName, EMPLOYEE.FirstName
FROM EMPLOYEE, PROPERTY, SERVICE
WHERE EMPLOYEE.EmployeeID = SERVICE.EmployeeID
AND SERVICE.PropertyID = PROPERTY.PropertyID
AND PROPERTY.City = 'Boston'
GROUP BY EMPLOYEE.LastName, EMPLOYEE.FirstName;
答案 0 :(得分:1)
尝试以下查询:
SELECT DISTINCT e.EmployeeId, e.FirstName, e.LastName
FROM EMPLOYEE e
INNER JOIN SERVICE s
ON e.EmployeeID = s.EmployeeID
INNER JOIN PROPERTY p
ON s.PropertyID = p.PropertyID
WHERE p.City = 'Boston'
请注意,我在这里使用了SELECT DISTINCT
,因为给定的员工可能与多个服务和属性相关联,但我们只想报告每个匹配的员工一次。
答案 1 :(得分:0)
员工通过EmployeeID链接到Service
服务通过物业ID链接到物业。
例如,假设您的表中有以下记录
Employee Table
+ ---------- + ----------- + ----------- +
| EmployeeID | Lastname | Firstname |
+ ---------- + ----------- + ----------- +
| 1 | Biegeleisen | Tim |
| 2 | Oropeza | Juan Carlos |
| 3 | Anderson | Jason |
+ ---------- + ----------- + ----------- +
Service Table
+ ---------- + ---------- +
| EmployeeID | PropertyID |
+ ---------- + ---------- +
| 1 | 3 |
| 2 | 2 |
| 3 | 2 |
+ ---------- + ---------- +
Property Table
+ ---------- + ---------- +
| PropertyID | City |
+ ---------- + ---------- +
| 1 | Seattle |
| 2 | Boston |
| 3 | San Jose |
+ ---------- + ---------- +
您可以使用联接使用如下查询将这些表组合在一起:
select e.*, p.city
from Employee e
inner join Service s on s.employeeID = e.EmployeeID
inner join Property p on p.propertyID = s.propertyID
给你这个表
Joined Table
+ ---------- + ----------- + ----------- + -------- +
| EmployeeID | Lastname | Firstname | City |
+ ---------- + ----------- + ----------- + -------- +
| 1 | Biegeleisen | Tim | San Jose |
| 2 | Oropeza | Juan Carlos | Boston |
| 3 | Anderson | Jason | Boston |
+ ---------- + ----------- + ----------- + -------- +
并且您要在此新表上应用过滤。
select e.Lastname, e.Firstname
from Employee e
inner join Service s on s.employeeID = e.EmployeeID
inner join Property p on p.propertyID = s.propertyID
where p.city = 'Boston'
根据评论和其他答案,您可以使用选择不同的或组来获得截然不同的结果。
选择区别:
select distinct e.Lastname, e.Firstname
from Employee e
inner join Service s on s.employeeID = e.EmployeeID
inner join Property p on p.propertyID = s.propertyID
where p.city = 'Boston'
分组依据:
select e.Lastname, e.Firstname
from Employee e
inner join Service s on s.employeeID = e.EmployeeID
inner join Property p on p.propertyID = s.propertyID
where p.city = 'Boston'
group by e.Lastname, e.Firstname