根据另一个表更新行

时间:2012-08-28 19:20:29

标签: sql oracle11g sql-update

我有一张表可以跟踪库存中链轮的物理质量。

create table sprockets(
    id NUMBER,
    mass NUMBER
);

INSERT into sprockets VALUES (1, 4);
INSERT into sprockets VALUES (2, 8);
INSERT into sprockets VALUES (3, 15);
INSERT into sprockets VALUES (4, 16);
INSERT into sprockets VALUES (5, 23);
INSERT into sprockets VALUES (6, 42);

我使用链轮机械装置对链轮进行日常维护。如果他们的修改使链轮的质量发生变化,他们会在维护报告中记下它。

create table maintenance_events(
    sprocket_id NUMBER,
    new_mass NUMBER
);

--chipped a widget off of sprocket #1; mass reduced to 3 kg
INSERT into maintenance_events VALUES (1, 3);       
--new lead bearings makes sprocket #2 weigh 413 kg
INSERT into maintenance_events VALUES (2, 413);     

我希望使用每个链轮的当前质量更新sprockets表。我想在new_mass中取maintenance_events并覆盖mass中的旧sprockets值。我提到了this question的前两个答案,但都给出了错误。

UPDATE sprockets
set mass = maintenance_events.new_mass
from sprockets, maintenance_events
where sprockets.id = maintenance_events.sprocket_id

Error at Command Line:2 Column:38
Error report:
SQL Error: ORA-00933: SQL command not properly ended

UPDATE sprockets
set sprockets.mass = maintenance_events.new_mass
from sprockets
INNER JOIN maintenance_events
on sprockets.id = maintenance_events.sprocket_id

Error at Command Line:2 Column:48
Error report:
SQL Error: ORA-00933: SQL command not properly ended

我做错了什么?

3 个答案:

答案 0 :(得分:3)

这是merge,一个upsert,用于:

merge into sprockets s
using ( select * from maintenance_events ) m
on (s.id = m.sprocket_id)
when matched then
 update 
    set s.mass = m.new_mass
        ;

使用where not exists等进行多次表扫描效率要高得多。

这是一个SQL Fiddle来证明它有效。

答案 1 :(得分:2)

这个怎么样?

UPDATE sprockets
SET sprockets.mass = (select new_mass 
                           from maintenance_events 
                      where sprockets.id = maintenance_events.sprocket_id)
WHERE EXISTS (select new_mass 
                           from maintenance_events 
                      where sprockets.id = maintenance_events.sprocket_id);

答案 2 :(得分:1)

试试这个:

UPDATE sprockets
set mass = (select maintenance_events.new_mass
from maintenance_events
where sprockets.id = maintenance_events.sprocket_id) where exists 
(select maintenance_events.sprocket_id from maintenance_events 
 where sprockets.id = maintenance_events.sprocket_id);

您可以在此处查看:http://sqlfiddle.com/#!5/f4262/11/0