尝试更新设置值时标量全选的结果多于一行

时间:2017-09-29 06:45:31

标签: sql db2 sql-update

所以我正在尝试设置Overtime_Total的值。要计算overtime_Total,你需要将Overtime_hours(来自表Overtime)和Overtime_Rate(来自表Employee_type)相乘。这是问题,当我尝试使用以下命令(命令1)设置值时,我得到如下错误。但是,当我使用另一个命令(Command)时,它显示与其ID匹配的值。

命令1

update Overtime
set Overtime_total = 
(SELECT (OVERTIME.OVERTIME_HOURS * EMPLOYEE_TYPE.OVERTIME_RATE)AS OVERTIME_TOTAL
FROM OVERTIME
INNER JOIN EMPLOYEE_TYPE ON OVERTIME.EMP_TYPE_ID = EMPLOYEE_TYPE.EMP_TYPE_ID
INNER JOIN SALARY ON SALARY.SALARY_ID = OVERTIME.SALARY_ID);

COmmand 2

(SELECT Overtime.Overtime_ID,(OVERTIME.OVERTIME_HOURS * EMPLOYEE_TYPE.OVERTIME_RATE)AS OVERTIME_TOTAL
FROM OVERTIME
INNER JOIN EMPLOYEE_TYPE ON OVERTIME.EMP_TYPE_ID = EMPLOYEE_TYPE.EMP_TYPE_ID
INNER JOIN SALARY ON SALARY.SALARY_ID = OVERTIME.SALARY_ID);

错误

The result of a scalar fullselect, SELECT INTO statement, or VALUES
INTO statement is more than one row.. SQLCODE=-811, SQLSTATE=21000

Table Overtime

Table Employee_type

1 个答案:

答案 0 :(得分:1)

您需要在子查询中给出主表id的条件

 update Overtime ot 
    set Overtime_total = 
    (SELECT (t1.OVERTIME_HOURS * emp.OVERTIME_RATE)AS OVERTIME_TOTAL
    FROM OVERTIME t1
    INNER JOIN EMPLOYEE_TYPE emp ON t1.EMP_TYPE_ID = emp.EMP_TYPE_ID
    INNER JOIN SALARY sal ON sal.SALARY_ID = t1.SALARY_ID where t1.EMP_TYPE_ID=ot.EMP_TYPE_ID and t1.overtime_id=ot.overtime_id);

你也可以使用merge,这比上面的方法

更快
merge into Overtime ot
using(
SELECT t1.overtime_id,t1.EMP_TYPE_ID,(t1.OVERTIME_HOURS * emp.OVERTIME_RATE)AS OVERTIME_TOTAL
FROM OVERTIME t1
INNER JOIN EMPLOYEE_TYPE emp ON t1.EMP_TYPE_ID = emp.EMP_TYPE_ID
INNER JOIN SALARY sal ON sal.SALARY_ID = t1.SALARY_ID) st
on ot.EMP_TYPE_ID=st.EMP_TYPE_ID and ot.overtime_id=st.overtime_id
when matched then update set ot.Overtime_total=st.OVERTIME_TOTAL;