mysql子查询存到另一张表,在MySQL中使用子查询到同一个表

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.

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值