mysql> select * from employees as e union all salary as s on e.employee_id=s.employee_id where employee_id in (select employee_id from salary where year(date)=2018 group by employee_id having sum(basic+bonus)>300000);
时间: 2024-03-18 09:44:00 浏览: 15
这是一条 MySQL 查询语句,查询了两张表 employees 和 salary,将它们的结果合并,并筛选出在 salary 表中,基本工资和奖金总和超过 300000 的员工的信息。具体来说,查询了 employees 表中所有员工的信息,以及 salary 表中所有员工在 2018 年的薪资信息,并将它们合并起来。最后,根据条件筛选出符合要求的员工信息。
相关问题
select dept_id,name,basic+bonus from salary inner join employees on salary.employee_id=employee.employee_id where dept_id=( select employee_id from employees where dept_id=( select dept_id from departments where dept_name='人事部' )) and year(date)=2018 and month(date)=12; ERROR 1054 (42S22): Unknown column 'employee.employee_id' in 'on clause'
在这个SQL语句中,出现了另一个错误,提示“Unknown column 'employee.employee_id' in 'on clause'”。这个错误通常表示在ON子句中使用了不存在的列名或表别名。在这个情况下,问题在于在ON子句中使用了employee.employee_id列,但是没有为employee表指定别名。
为了解决这个问题,需要为employee表指定一个别名,并在ON子句中使用它。下面是修正后的SQL语句:
```
select s.dept_id, e.name, s.basic+s.bonus
from salary s
inner join employees e on s.employee_id = e.employee_id
where s.dept_id = (
select employee_id from employees where dept_id = (
select dept_id from departments where dept_name = '人事部'
)
) and year(s.date) = 2018 and month(s.date) = 12;
```
在这个修正后的SQL语句中,我们为employee表指定了别名e,并在ON子句和SELECT子句中使用它。这样就能够正确地查询部门名称为“人事部”、时间为2018年12月份的员工的工资信息。
select dept_id,name,basic+bonus from salary inner join employees on salary.employee_id=employees.employee_id where dept_id=( select employee_id from employees where dept_id=( select dept_id from departments where dept_name='人事部' )) and year(date)=2018 and month(date)=12; ERROR 1242 (21000): Subquery returns more than 1 row
在这个SQL语句中,出现了错误“Subquery returns more than 1 row”,它通常表示子查询返回了多行数据。在这个情况下,问题在于第一个子查询返回了多个employee_id值,而不是单个值,因此无法将其用作外部查询中的条件。
为了解决这个问题,可以考虑使用IN运算符而不是等号来比较子查询返回的值。下面是修正后的SQL语句:
```
select s.dept_id, e.name, s.basic+s.bonus
from salary s
inner join employees e on s.employee_id = e.employee_id
where s.dept_id IN (
select employee_id from employees where dept_id = (
select dept_id from departments where dept_name = '人事部'
)
) and year(s.date) = 2018 and month(s.date) = 12;
```
在这个修正后的SQL语句中,我们使用IN运算符来比较子查询返回的值。这样就能够正确地查询部门名称为“人事部”、时间为2018年12月份的员工的工资信息。