Employee?表包含所有員工,他們的經理也屬于員工。每個員工都有一個 Id,此外還有一列對應員工的經理的 Id。
+----+-------+--------+-----------+
| Id | Name ?| Salary | ManagerId |
+----+-------+--------+-----------+
| 1 ?| Joe ? | 70000 ?| 3 ? ? ? ? |
| 2 ?| Henry | 80000 ?| 4 ? ? ? ? |
| 3 ?| Sam ? | 60000 ?| NULL ? ? ?|
| 4 ?| Max ? | 90000 ?| NULL ? ? ?|
+----+-------+--------+-----------+
給定?Employee?表,編寫一個 SQL 查詢,該查詢可以獲取收入超過他們經理的員工的姓名。在上面的表格中,Joe 是唯一一個收入超過他的經理的員工。
+----------+
| Employee |
+----------+
| Joe ? ? ?|
+----------+
思路:
自連接
# Write your MySQL query statement below
select A.Name as 'Employee'
from Employee as A,Employee as B
where A.ManagerId=B.Id and A.Salary>B.Salary;
子查詢包含主查詢內容的效率比較慢,所以不推薦使用。
select a.name as Employee
from Employee as a
where a.salary > (select b.salary from Employee as b where b.id = a.managerid);
?