使用唯一ID连接表

时间:2014-03-21 03:46:48

标签: mysql sql

您好,我在一家福利公司工作,我需要一个通过员工SSN连接三个数据表的查询。例如,

一个表只有员工数据。

EmployeeSSN SSN            Status      FirstName   LastName
111-11-1111 111-11-1111    Employee    John        Smith
222-22-2222 222-22-2222    Employee    David       Gonzales
333-33-3333 333-33-3333    Employee    Eric        Moore

一张表有依赖数据(配偶)

EmployeeSSN SSN            Status      FirstName   LastName
111-11-1111 777-77-7777    Spouse      Dina        Smith
222-22-2222 888-88-8888    Spouse      Niki        Gonzales
333-33-3333 999-99-9999    Spouse      Carla       Moore

一个表具有从属数据(子)

EmployeeSSN SSN            Status     FirstName    LastName
111-11-1111 444-44-4444    Child         Cindy         Smith 
222-22-2222 555-55-5555    Child         Calob         Gonzales
333-33-3333 666-66-6666    Child         Kevin         Moore

我需要的东西看起来像是最终输出(下图)。 EmployeeSSN将员工和受抚养人联系在一起。我已经尝试了联合语句和数据透视语句,仍在学习SQL,因此遇到了很多问题。任何帮助将不胜感激。

EmployeeSSN     SSN          Relation   Last Name     First Name
111-11-1111    111-11-1111   Employee    John           Smith
111-11-1111    777-77-7777   Spouse      Dina           Smith
111-11-1111    444-44-4444   Child       Cindy          ANDRE

3 个答案:

答案 0 :(得分:0)

试试这个.......

(SELECT EmployeeSSN,SSN,Relation,Last Name,First Name FROM Employee where EmployeeSSN=111-11-1111)
union
(SELECT EmployeeSSN,SSN,Relation,Last Name,First Name FROM Spouse where EmployeeSSN=111-11-1111)
union
(SELECT EmployeeSSN,SSN,Relation,Last Name,First Name FROM Child where EmployeeSSN=111-11-1111)

答案 1 :(得分:0)

这对我有用.. !!!

  SELECT EmployeeSSN,SSN,Status As Relation,FirstName,LastName 
  FROM TABLE1 A,TABLE2 B,TABLE3 C where 
  A.EmployeeSSN = B.EmployeeSSN,B.EmployeeSSN = C.EmployeeSSN;

答案 2 :(得分:0)

这将为您提供所需的输出:

(SELECT EmployeeSSN, SSN, 'Employee' Relation, LastName, FirstName FROM EmployeeTable WHERE EmployeeSSN=111-11-1111)
UNION
(SELECT EmployeeSSN, SSN, 'Spouse' Relation, LastName, FirstName FROM SpouseTable EmployeeSSN=111-11-1111) 
UNION
(SELECT EmployeeSSN, SSN, 'Child' Relation, LastName, FirstName FROM DependentTable EmployeeSSN=111-11-1111)

请注意,“Relation”列是从每个子查询中的字符串分配的。这会根据每个记录的原始表格为每个记录指定正确的关系。