1

这是架构:

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(每个部门名称一个)吗?

提前致谢!

4

3 回答 3

2

它正在做你认为它正在做的事情。问题是你的数据不是你想象的那样。表中所有条目的department_idemployees相同,1。所以每个部门得到一个值,问题是只代表一个部门。

这是一个SQLfiddle来说明这一点。我已经扩充了您的架构,但未修改查询。

于 2013-08-03T18:32:06.423 回答
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

此查询将返回每个部门中具有最高薪水的员工列表。如果您想查看多个部门的信息 - 只需用更多员工填写另一个部门(根据您的陈述,您的员工仅在部门 ID = 1 的部门中)

于 2013-08-03T18:37:28.813 回答
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

请注意,如果您使用不在 group by 中的列(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
        )
于 2013-08-03T18:29:40.400 回答