SQL查询多个表问题

时间:2015-06-04 19:18:04

标签: mysql sql sql-server select

我有3个表,孩子,员工和部门,有一些样本数据。我需要抓取:

  1. 子名称
  2. 相应员工的名字和姓氏
  3. 该员工经理的名字和姓氏。
  4. 我想根据上述标准将列中的数据分开。

    子表:

    +-----------+-------+
    | empld_id  | name  |
    +-----------+-------+
    | 123456789 | Manny |
    | 333445555 | Joy   |
    | 987654321 | abner |
    +-----------+-------+
    

    员工表:

    +-------+-------+-----------+-----+-----------+--------+
    | fname | lname |    ssn    | sex | superssn  | deptNo |
    +-------+-------+-----------+-----+-----------+--------+
    | john  | smith | 123456789 | m   | 333445555 |      5 |
    +-------+-------+-----------+-----+-----------+--------+
    

    部门表:

    +-----------------+--------+------------+
    | department_name | deptNo | managerssn |
    +-----------------+--------+------------+
    | HQ              |      1 | 8888665555 |
    | admin           |      4 | 9876543211 |
    +-----------------+--------+------------+
    

    我目前有这个查询:

    select 
      A.name,
      B.fname, 
      B.lname 
    from 
      child A, 
      employee B, 
      department C
    where 
      A.empld_id= B.ssn and 
      C.managerssn = B.ssn;
    

1 个答案:

答案 0 :(得分:3)

你几乎就在那里 - 你有经理的SSN - 现在你需要做的就是把它加回到员工表来获取他的详细信息。

继续查询的样式:

SELECT c.name, 
       e.fname, e.lname, 
       m.fname AS manager_fname, m.lname AS manager_lname
FROM   child c, employee e, department d, employee m
WHERE  c.empid_id = e.ssn AND d.managerssn = e.ssn AND m.ssn = d.managerssn

但请注意,隐式连接(在from子句中有多个表)已经被弃用了很长一段时间,建议避免它们并使用显式join代替:

SELECT c.name, 
       e.fname, e.lname, 
       m.fname AS manager_fname, m.lname AS manager_lname
FROM   child c
JOIN   employee e ON c.empid_id = e.ssn
JOIN   department d ON d.managerssn = e.ssn
JOIN   employee m ON m.ssn = d.managerssn