Using subquery for the same table in MySQL

不羁的心 提交于 2019-12-02 11:39:24

问题


I have a table called Staff which has the following fields: idStaff, Name, Phone, Email, SupervisorId.

The SuervisorId is the idStaff of that staff member's supervisor.

I want to show the list of all staff members with their basic info (Name, Email etc) as well as the name of their supervisor.

So something like this:

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

The query does not work. I tried joining the two tables but I am confused on how to get the Name from the subquery in the join.

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

Any help will be much appreciated.


回答1:


Maybe something like this....

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

or you could have done something like....

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



回答2:


LEFT JOIN is your friend. Try a query like this. Look at the aliases s(taff) and 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;


来源:https://stackoverflow.com/questions/37091456/using-subquery-for-the-same-table-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!