leecode的題目。關於in的應用。感覺很經典,這裡列出解題過程。
employee 表包含所有員工資訊,每個員工有其對應的 id, salary 和 department id。
sql如下:
set names utf8mb4;
set foreign_key_checks =0;
-- ----------------------------
-- table structure for employee
-- ----------------------------
drop
table
ifexists
`employee`
;create
table
`employee`
(`id`
int(11)
notnull
auto_increment
,`name`
varchar
(255
)character
set utf8mb4 collate utf8mb4_0900_ai_ci null
default
null
,`salary`
int(
255)
null
default
null
,`departmentid`
int(
255)
null
default
null
,primary
key(
`id`
)using
btree
)engine
=innodb
character
set= utf8mb4 collate
= utf8mb4_0900_ai_ci row_format = dynamic;
-- ----------------------------
-- records of employee
-- ----------------------------
insert
into
`employee`
values(1
,'joe'
,70000,1
);insert
into
`employee`
values(2
,'jim'
,90000,1
);insert
into
`employee`
values(3
,'henry'
,80000,2
);insert
into
`employee`
values(4
,'sam'
,60000,2
);insert
into
`employee`
values(5
,'max'
,90000,1
);set foreign_key_checks =
1;
department 表包含公司所有部門的資訊。
set names utf8mb4;
set foreign_key_checks =0;
-- ----------------------------
-- table structure for department
-- ----------------------------
drop
table
ifexists
`department`
;create
table
`department`
(`id`
int(11)
notnull
auto_increment
,`name`
varchar
(255
)character
set utf8mb4 collate utf8mb4_0900_ai_ci null
default
null
,primary
key(
`id`
)using
btree
)engine
=innodb
character
set= utf8mb4 collate
= utf8mb4_0900_ai_ci row_format = dynamic;
-- ----------------------------
-- records of department
-- ----------------------------
insert
into
`department`
values(1
,'it');
insert
into
`department`
values(2
,'sales');
set foreign_key_checks =
1;
方法:使用 join 和 in 語句
演算法因為 employee 表包含 salary 和 departmentid 字段,我們可以以此在部門內查詢最高工資。
select
departmentid,
max(salary)
from
employee
group
by departmentid;
注意:有可能有多個員工同時擁有最高工資,所以最好在這個查詢中不包含雇員名字的資訊。departmentid
max(salary)
190000
280000
然後,我們可以把錶 employee 和 department 連線,再在這張臨時表裡用 in 語句查詢部門名字和工資的關係。
部門工資最高的員工
employee表包含所有員工資訊,每個員工有其對應的 id,salary 和 department id。id name salary departmentid 1 joe 70000 1 2 henry 80000 2 3 sam 60000 2 4 max 90000 1 department...
LeetCode SQL 部門工資最高的員工
employee 表包含所有員工資訊,每個員工有其對應的 id,salary 和 department id。id name salary departmentid 1 joe 70000 1 2 henry 80000 2 3 sam 60000 2 4 max 90000 1 departmen...
leetcode 求部門工資最高的員工
employee表包含所有員工資訊,每個員工有其對應的 id,salary 和 department id。id name salary departmentid 1 joe 70000 1 2 henry 80000 2 3 sam 60000 2 4 max 90000 1 department...