[英]Updating rows based on another table
我創建了一個名為SALE_REP
表,該表包含4列employee_id
, name
, salary
和commission_pct
。
我從現有的EMPLOYEES
表中填充了SALE_REP
表。 現在,我想基於另一個表中的值,使用子查詢來更新SALE_REP
表中某些員工的薪水。
update sale_rep
set salary = (select salary from employees
where job_id = 'ad_vp')
where employee_id = (select employee_id from employees
where commission_pct = 0.35);
但這得到了;
SQL Error: ORA-01427: single-row subquery returns more than one row
01427. 00000 - "single-row subquery returns more than one row"
*Cause:
*Action:
我在做什么錯,如何成功執行更新?
您有兩個子查詢,並且如果您的數據基於標准HR模式的employee表,則兩者都將返回多行。
第二個很簡單; =
必須in
:
where employee_id in (select employee_id from employees
where commission_pct = 0.35)
...與我的架構中的employee
表中的三行匹配。 (盡管正如您所說的, sale_rep
表是從employees
sale_rep
填充的,並且具有commission_pct
列,但您實際上並不需要在這里使用子查詢-過濾器值存在於您要更新的表上,因此您可以只在where commission_pct = 0.35
)。
第一個比較困難,您需要定義實際要發生的事情。 例如,您可以從與指定的job_id
匹配的人中選擇最高薪水:
set salary = (select max(salary) from employees
where job_id = 'SA_REP')
我選擇了'SA_REP'
因為它看起來像是銷售代表,並且在我的模式中有30個匹配的行,其中包含20個不同的值。 根據您的編輯,我的架構中有兩行用於AD_VP
,但是兩者的薪水相同; 在這種情況下,使用max()
可能沒問題,或者您可以使用distinct
:
set salary = (select distinct salary from employees
where job_id = 'AD_VP')
但這是針對此時您所擁有數據的非常特定的信息,因此這並不是一個好的通用模式。
將這些放在一起,您可以執行以下操作:
select employee_id, salary from sale_rep where commission_pct = 0.35;
EMPLOYEE_ID SALARY
----------- ----------
156 10000
157 9500
158 9000
update sale_rep
set salary = (select max(salary) from employees
where job_id = 'AD_VP')
where employee_id in (select employee_id from employees
where commission_pct = 0.35);
3 rows updated.
select employee_id, salary from sale_rep where commission_pct = 0.35;
EMPLOYEE_ID SALARY
----------- ----------
156 17000
157 17000
158 17000
通常,您要更新的行與您選擇的值之間可能需要建立某種聯系,而不是佣金百分比過濾器,這看起來與工作無關。 在這種情況下,這似乎確實是您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.