超出經理收入的員工

2021-10-24 13:09:12 字數 2236 閱讀 6981

create

table

ifnot

exists employee (id int

, name varchar

(255

), salary int

, managerid int

)truncate

table employee

insert

into employee (id, name, salary, managerid)

values

('1'

,'joe'

,'70000'

,'3'

)insert

into employee (id, name, salary, managerid)

values

('2'

,'henry'

,'80000'

,'4'

)insert

into employee (id, name, salary, managerid)

values

('3'

,'sam'

,'60000'

,'none'

)insert

into employee (id, name, salary, managerid)

values

('4'

,'max'

,'90000'

,'none'

)

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 |

+----------+

演算法

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

select

*from employee as a, employee as b

;

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

select

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

employee as b

where

a.managerid = b.id

and a.salary > b.salary

;

演算法

實際上, 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

;

超過經理收入的員工

create table employee id number 10 primary key,name varchar 10 not null salary number 10 managerid number 10 insert into employee values 1 jon 70000,3...

超過經理收入的員工

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 給定em...