这是架构:
CREATE TABLE `employees` (
`employee_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`department_id` int(11) DEFAULT NULL,
`boss_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`salary` varchar(255) DEFAULT NULL,
PRIMARY KEY (`employee_id`)
);
CREATE TABLE `departments` (
`department_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`department_id`)
);
这是数据集:
INSERT INTO `employees` (`employee_id`, `department_id`, `boss_id`, `name`, `salary`)
VALUES
(1,1,0,'manager','80000'),
(2,1,1,'emp1','60000'),
(3,1,1,'emp2','50000'),
(4,1,1,'emp3','95000'),
(5,1,1,'emp4','75000');
INSERT INTO `departments` (`department_id`, `name`)
VALUES
(1,'IT'),
(2,'HR'),
(3,'Sales'),
(4,'Marketing');
练习题:列出部门薪水最高的员工。
这是我的疑问:
select e.name as 'employee name',max(e.salary) as 'salary',d.name as 'dept name'
from employees e join departments d
on e.department_id=d.department_id
group by d.name
为什么我的查询只返回一行?它不应该返回4(每个部门名称一个)?
提前致谢!
答案 0 :(得分:2)
它正在做你认为正在做的事情。问题是你的数据不是你想象的那样。 employees
表中所有条目的department_id都相同,1
。因此,每个部门获得一个值,问题是只代表一个部门。
这是一个SQLfiddle来说明这一点。我已经扩充了你的模式,但保持了查询不被修改。
答案 1 :(得分:1)
SELECT
d.name,
e.name,
e.salary
FROM employees e
INNER join departments d on e.department_id=d.department_id
INNER JOIN (
SELECT
d.department_id,
max(e.salary) as salary
from departments d
left join employees e on e.department_id=d.department_id
group by d.department_id
) x ON x.salary = e.salary AND d.department_id = x.department_id
此查询将返回每个部门中具有最高薪水的员工列表。如果您想查看多个部门的信息 - 只需填写更多员工的其他部门(根据您的陈述,您只有部门中的员工,department_id = 1)
答案 2 :(得分:0)
inner join
仅返回on
条件匹配的行。由于只有一个部门有员工,因此只返回该部门。
要选择所有部门,请使用left join
:
select e.name as 'name of a random employee'
, max(e.salary) as 'max salary'
, d.name as 'dept name'
from departments d
left join
employees e
on e.department_id=d.department_id
group by
d.name
请注意,如果您使用不在组中的列(如上面的e.name
),则基本上会获得随机值。它不会总是返回薪水最高的员工的姓名。
要返回薪水最高的员工姓名,您可以:
select e.name as 'name of a employee with max salary'
, e.salary as 'max salary'
, d.name as 'dept name'
from departments d
left join
employees e
on e.department_id=d.department_id
where e.name is null
or e.salary =
(
select max(salary)
from employees e2
where e.department_id = e2.department_id
)