181 超過經理收入的員工

2021-10-09 21:10:58 字數 1581 閱讀 7057

employee 表包含所有員工,他們的經理也屬於員工。每個員工都有乙個 id,此外還有一列對應員工的經理的 id。

解釋一下題目

id:1,2對應的salary表示作為員工的工資; managerid對應下面id為3,4。3,4裡的salary則是作為經理的工資,此表中只有joe作為員工時70000>他作為經理時的60000。

±—±------±------------±------------------+

| 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 |

±---------+

方法 1:使用 where 語句

演算法如下面**所示,**裡存有每個雇員經理的資訊,我們也許需要從這個表裡獲取兩次資訊。

#mysql

select

*from employee as a, employee as b

;

從兩個表裡使用 select 語句可能會導致產生 笛卡爾乘積 。在這種情況下,輸出會產生 4*4=16 個記錄。然而我們只對雇員工資高於經理的人感興趣。

所以我們應該用 where 語句加 2 個判斷條件;由於我們只需要輸出雇員的名字,優化上面的**,得到最終解法:

select

a.name as

'employee'

from

employee as a,

employee as b

where

a.managerid = b.id

and a.salary > b.salary

;

方法 2:使用 join 語句

演算法實際上, join 是乙個更常用也更有效的將錶連起來的辦法,我們使用 on 來指明條件。

select

a.name as employee

from employee as a join employee as b

on a.managerid = b.id

and a.salary > b.salary

;

181 超過經理收入的員工

employee表包含所有員工,他們的經理也屬於員工。每個員工都有乙個 id,此外還有一列對應員工的經理的 id。id name salary managerid 1 joe 70000 3 2 henry 80000 4 3 sam 60000 null 4 max 90000 null 給定em...

181 超過經理收入的員工

employee 表包含所有員工,他們的經理也屬於員工。每個員工都有乙個 id,此外還有一列對應員工的經理的 id。id name salary managerid 1 joe 70000 3 2 henry 80000 4 3 sam 60000 null 4 max 90000 null 給定 ...

181 超過經理收入的員工

employee 表包含所有員工,他們的經理也屬於員工。每個員工都有乙個 id,此外還有一列對應員工的經理的 id。id name salary managerid 1 joe 70000 3 2 henry 80000 4 3 sam 60000 null 4 max 90000 null 給定 ...