在MySQL中使用子查询到同一个表

时间:2016-05-07 17:16:28

标签: php mysql join inner-join

我有一个名为Staff的表格,其中包含以下字段:idStaff, Name, Phone, Email, SupervisorId

SuervisorId是该工作人员主管的idStaff

我想显示所有员工的名单及其基本信息(姓名,电子邮件等)以及他们的主管姓名。

这样的事情:

select idStaff
     , Name
     , Email
     , Phone
     , (select Name from Staff where idStaff = SupervisorId) as SupervisorName 
  from Staff 
 order 
    by Name ASC

查询不起作用。我尝试加入这两个表,但我很困惑如何从连接中的子查询中获取名称。

 select idStaff
      , Name
      , Phone
      , Email 
   from Staff a 
  inner 
   join Staff b 
     on a.idStaff = b.SupervisorId 
  order 
     by Name ASC

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

也许是这样的......

select s1.idStaff
     , s1.Name
     , s1.Email
     , s1.Phone
     , s2.Name as SupervisorName 
from Staff s1
LEFT JOIN Staff s2 ON s1.SupervisorId = s2.idStaff
 order 
    by s1.Name ASC

或者你可以做类似......

select s.idStaff
     , s.Name
     , s.Email
     , s.Phone
     , (select top 1 m.Name from Staff m 
                            where  s.SupervisorId =  m.idStaff) as SupervisorName 
from Staff s
order by s.Name ASC

答案 1 :(得分:0)

LEFT JOIN是你的朋友。尝试这样的查询。查看别名s(taff)和m(ember)

SELECT m.idStaff
     , m.Name
     , m.Email
     , m.Phone
     , s.Name
  FROM Staff m
  LEFT JOIN Staff s ON s.idStaff = m.SupervisorId
  ORDER BY m.Name ASC;