列出分配给“东伦敦十字路口”项目的所有已婚雇员及其配偶的姓名

时间:2019-01-09 14:50:28

标签: mysql join self-join

Project   Table Pk(project Number)

Project Table

 Marriage Table : PK (EmployeeNumber)
 Fk_ Marriage - employee (spouseNumber) 

Marriage Table

Employee Table (EmployeeNumber) 

Employee Table

Workon Table : PK(EmployeeNumber,ProjectNumber,CityCode) 
              FK_ Workon - employee (EmployeeNumber)
              FK_ Workon - project (projectNumber)

Workon Table

1 Table : Project  pk(project Number)
2 Table : Marriage PK (EmployeeNumber) 
          Fk_ Marriage - employee (spouseNumber)
3 Table : Employee(EmployeeNumber) 
4 Table : Workon PK(EmployeeNumber,ProjectNumber,CityCode) 
          FK_ Workon - employee (EmployeeNumber)
          FK_ Workon - project (projectNumber)

   List the names of all married employees and their spouses who are assigned to the “East London Crossing” project

加入是有可能的,或者我们需要做更多的工作来解决爱情问题

3 个答案:

答案 0 :(得分:0)

使用联接可以解决此问题-实际上,由于您要检索的组件位于单独的表中,因此通常需要联接。

您将需要将Project表与Employee表和Workon表联接。婚姻表本质上是不相关的,因为其信息已经存在于员工表中。在SQL中,这是笛卡尔乘积(FROM),其中强制/选择了某些约束(WHERE)。

例如(假设丈夫和妻子都在ELC上工作):

global scopes

(注意:我尚未实际测试此代码,因此可能存在语法错误)

或者,您可以选择使用自然联接,在这种情况下,可以将诸如Project和Workon之类的表联接在一起(例如SELECT E1.FirstName, E1.LastName, E2.FirstName, E2.LastName FROM Project P, Workon W1, Workon W2, Employee E1, Employee E2 WHERE P.projectNumber = W1.projectNumber AND P.projectNumber = W2.projectNumber AND W1.employeeNumber = E1.EmployeeNumber AND W2.employeeNumber = E2.EmployeeNumber AND E1.SpouseNumber = E2.EmployeeNumber AND P.name = "East London Crossing"; )。

答案 1 :(得分:0)

您需要两次使用表workon和employee来同时加入id

SELECT e1.FirstName
    , e1.LastName
    , e2.FirstName
    , e2.LastName 
FROM Project p
INNER JOIN  Workon w1 ON  p.projectNumber = w1.projectNumber 
INNER JOIN Workon W2 ON p.projectNumber = W2.projectNumber 
INNER JOIN Employee e1 ON  w1.employeeNumber = e1.EmployeeNumber
INNER JOIN Employee e2 ON W2.employeeNumber = e2.EmployeeNumber  
    AND e1.SpouseNumber = e2.EmployeeNumber
WHERE p.id = 2 

答案 2 :(得分:0)

范安德鲁我修改了您的代码

SELECT E.EmployeeNumber,E.FirstName, E.LastName,
       E.SpouseNumber, w.projectNumber,P.name
       FROM Project P, Workon W, Employee E 
       WHERE P.projectNumber = W.projectNumber AND
             W.employeeNumber = E.EmployeeNumber  
             AND P.name = "East London Crossing" AND 
                 E.SpouseNumber is not NULL;