我需要根据另一个表更新表,所以我有声明:
update FAULTS
set FAULTS.FAULT_STATE = (
select INCIDENTS.TICKET_STATE from INCIDENTS
where INCIDENTS.CF_ID = FAULTS.CF_ID
)
它给我错误的说法:
ORA-01427: single-row subquery returns more than one row
我尝试过DISTINCT,但状态值也不同,所以DISTINCT不起作用。所以我也改了它:
update FAULTS
set FAULTS.FAULT_STATE = (
select INCIDENTS.TICKET_STATE from INCIDENTS
where INCIDENTS.CF_ID = FAULTS.CF_ID and rownum = 1
)
现在它不会出错。
问题是,如果子查询返回null,它还将更新行并清除内容。对此有何解决方法?
答案 0 :(得分:1)
您可以确保只有匹配的行才会更新如下:
update FAULTS
set FAULTS.FAULT_STATE = (
select INCIDENTS.TICKET_STATE from INCIDENTS
where INCIDENTS.CF_ID = FAULTS.CF_ID and rownum = 1
)
where exists (
select INCIDENTS.TICKET_STATE from INCIDENTS
where INCIDENTS.CF_ID = FAULTS.CF_ID
)
答案 1 :(得分:0)
合并变体(10g +):
merge into faults
using (select cf_id, ticket_state from incidents) incidents
on (incidents.cf_id = faults.cf_id)
when matched then update
set fault_state=ticket_state;