MySQL自连接

如下emp表,id为员工编号,name为员工姓名,sup_id为上司编号

mysql> select * from emp;
+----+--------+--------+
| id | name   | sup_id |
+----+--------+--------+
|  1 | Job    |   NULL |
|  2 | Alex   |      1 |
|  3 | Jeffry |      2 |
|  4 | Tom    |      3 |
+----+--------+--------+
4 rows in set (0.00 sec)

现在我需要查询每个员工对应的上司姓名,可用自连接

mysql> select a.id,a.name,b.name
    -> from emp as a 
    -> left join emp as b
    -> on a.sup_id=b.id;
+----+--------+--------+
| id | name   | name   |
+----+--------+--------+
|  1 | Job    | NULL   |
|  2 | Alex   | Job    |
|  3 | Jeffry | Alex   |
|  4 | Tom    | Jeffry |
+----+--------+--------+
4 rows in set (0.00 sec)
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务