SQL Inner Join Tutorial with Example: Managers with at Least 5 D
- 时间:2020-10-05 13:15:44
- 分类:网络文摘
- 阅读:119 次
Given the following SQL Schema:
Create table If Not Exists Employee (Id int, Name varchar(255), Department varchar(255), ManagerId int)
Truncate table Employee
insert into Employee (Id, Name, Department, ManagerId) values ('101', 'John', 'A', 'None')
insert into Employee (Id, Name, Department, ManagerId) values ('102', 'Dan', 'A', '101')
insert into Employee (Id, Name, Department, ManagerId) values ('103', 'James', 'A', '101')
insert into Employee (Id, Name, Department, ManagerId) values ('104', 'Amy', 'A', '101')
insert into Employee (Id, Name, Department, ManagerId) values ('105', 'Anne', 'A', '101')
insert into Employee (Id, Name, Department, ManagerId) values ('106', 'Ron', 'B', '101')
The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.
+------+----------+-----------+----------+ |Id |Name |Department |ManagerId | +------+----------+-----------+----------+ |101 |John |A |null | |102 |Dan |A |101 | |103 |James |A |101 | |104 |Amy |A |101 | |105 |Anne |A |101 | |106 |Ron |B |101 | +------+----------+-----------+----------+Given the Employee table, write a SQL query that finds out managers with at least 5 direct report. For the above table, your SQL query should return:
+-------+ | Name | +-------+ | John | +-------+Note:
No one would report to himself.
How does SQL Inner-Join Work?
The SQL Inner-Join (or often referred to as Join) can be easily illustrated using the following Venn Diagram:

sql-joins-venn-diagrams-inner-join
Two tables are joined and the result is the intersection of two tables.
select Name from Employee as A
inner join (
select ManagerId
from Employee
group by ManagerId
having count(1) >= 5
) as B on A.ID = B.ManagerId
As we can see, two tables (queries) are joined using the keyword inner join (case insensitive) or join in short. You also need to specify the columns that connect two tables using syntax On.
SQL Sub Query
As of this problem, we can also use the sub query to solve.
select Name from Employee where Id in ( select ManagerId from Employee group by ManagerId having count(ManagerId) >= 5 )
This works slightly differently, the IDs from a query are returned and are used as inputs to another query (more or less like the pipe).
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:深圳卫视直播-深圳卫视在线直播观看「高清」 四川卫视直播-四川卫视在线直播观看「高清」 厦门卫视直播-厦门卫视在线直播观看「高清」 广西卫视直播-广西卫视在线直播观看「高清」 东南卫视直播-东南卫视在线直播观看「高清」 陕西卫视直播-陕西卫视在线直播观看「高清」 农林卫视直播-陕西农林卫视在线直播观看「高清」 贵州卫视直播-贵州卫视在线直播观看「高清」 云南卫视直播-云南卫视在线直播观看「高清」 江西卫视直播-江西卫视在线直播观看「高清」
- 评论列表
-
- 添加评论