我需要有关mysql查询的帮助

时间:2018-12-31 20:23:33

标签: mysql sql

我需要输入姓名和主管姓名

表名:用户

id | name |
-----------
 1 | David 
 2 | Frank
 3 | Shane
 4 | Franchich

另一个表格名称:详细信息

user_id | supervisor_id|
----------------------------
  1 | 4
  2 | 3
  3 | 4

我尝试过:

select 
    name as user name 
from user, details 
WHERE details.user_id=user.id 

但失败

现在我想得到类似的结果

User Name | Supervisor Name
------------------------------
David | Franchich
Frank | Shane
Shane | Franchich

那怎么可能?

2 个答案:

答案 0 :(得分:0)

您要在表详细信息和表用户之间寻找两个JOIN,例如:

select
    u1.name as user_name,
    u2.name as supervisor_name
from details d
inner  join user u1 on u1.id = d.user_id
inner  join user u2 on u2.id = d.supervisor_id

答案 1 :(得分:0)

您应该两次加入user表。您需要表别名来将user标识为“用户”(u),将user标识为“管理者”(m):

select 
     u.name as UserName, m.username as SupervisorName
from 
     user u
inner join 
     details   on u.id = details.user_id
inner join 
     user m    on details.supervisor_id = m.id