我是SQL的新手,我一直坚持查询。
我有3个表员工,部门和salary_paid。 我试图通过给出这个条件来更新salary_paid表中的奖励列
give 10% bonus on total salary to the employees who are not in IT departments.
我想出了这个查询
update salary_paid
set bonus=(select (0.1*total_salary) "Bonus"
from salary_paid, departments, employees
where
employees.department_id=departments.department_id and
employees.employee_id=salary_paid.employee_id and
departments.department_name!='IT')
;
但是它会返回此错误
ORA-01427:单行子查询返回多行
我对此完全无能为力,请帮忙。 提前致谢
答案 0 :(得分:1)
您的内部查询(select (0.1*total_salary) "Bonus" from salary_paid
返回的值不止一个,因此无法分配给bounus列。
而是尝试使用像这样的连接进行更新
UPDATE
(SELECT salary_paid.bonus as oldBonus, 0.1*salary_paid.total_salary as newBounus
FROM salary_paid
INNER JOIN employees
ON salary_paid.employee_id = employees.employee_id
INNER JOIN departments
ON departments.department_id = employees.department_id
WHERE departments.department_name != 'IT'
) t
SET t.oldBonus= t.newBounus
答案 1 :(得分:1)
试试这个:
UPDATE
(
SELECT *
FROM employees e LEFT JOIN salary_paid sp ON e.employee_id = sp.employee_id
LEFT JOIN departments d ON d.department_id = e.department_id
) t
SET t.bonus = 0.1 * t.total_salary
WHERE t.department_name != 'IT';
您的查询是使用子查询的结果更新表中的所有行。此外,子查询返回多行。设置值时,子查询应始终返回单列的单行
在Oracle中,这些问题通过使用join来解决,如上所示。这将使用相应bonus
列中的值更新total_salary
列。无需使用子查询。
答案 2 :(得分:0)
子查询应始终返回单行。但是你使用select查询来到这里多行。所以首先检查您的选择查询。
select (0.1*total_salary) "Bonus" from salary_paid, departments, employees
where employees.department_id=departments.department_id and employees.employee_id=salary_paid.employee_id and departments.department_name!='IT'
此查询应该只有一个结果,但是您正在尝试获取多行。
让我们尝试将 LIMIT 放入您的选择查询
select (0.1*total_salary) "Bonus" from salary_paid, departments, employees
where employees.department_id=departments.department_id and employees.employee_id=salary_paid.employee_id and departments.department_name!='IT' limit 0,1
您需要以这种方式更改您的选择查询。
答案 3 :(得分:0)
试试这个
update salary_paid a,departments b, employees c set a.bonus=(0.1*a.total_salary) "Bonus"
where c.department_id=b.department_id and c.employee_id=a.employee_id and b.department_name!='IT';
CMIIW
答案 4 :(得分:0)
我想在hr用户中更新电子邮件并遇到同样的问题然后我认为这对我有用
update (select email as oldemail, substr(first_name,1,1)||''||last_name||''||'@gmail.com' as email from employees
inner join departments
on
employees.department_id= departments.department_id
)t
set t.oldemail=t.email