列出所有已婚员工及其配偶的名字,他们被分配到“东伦敦穿越”项目

e7arh2l6  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(255)
Project   Table Pk(project Number)

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

Employee Table (EmployeeNumber)

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

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

这是可能的加入或我们需要做更多的加入到爱的问题

rks48beu

rks48beu1#

您需要使用表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
oyxsuwqo

oyxsuwqo2#

我修改了你的代码有多好

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;
wlwcrazw

wlwcrazw3#

使用联接可以解决这个问题—事实上,由于要检索的组件位于不同的表中,因此通常需要联接。
您需要将project表与employee表和workon表连接起来。婚姻表本质上是不相关的,因为它的信息已经存在于employee表中。在sql中,这是一个笛卡尔积(from),其中强制/选择了某些约束(where)。
例如(假设丈夫和妻子都在elc上工作):

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";

(注意:我还没有实际测试过这段代码,所以它可能有语法错误)
或者,您可以选择使用自然联接,在这种情况下,可以将project和workon等表联接在一起(例如。 Project NATURAL JOIN Workon ).

相关问题