2

我有一张表格,可以记录我库存中链轮的物理质量。

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我提到了这个问题的前两个答案,但都给出了错误。

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

我究竟做错了什么?

4

3 回答 3

3

这就是mergeupsert 的用途:

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它比使用etc进行多次表扫描要高效得多。

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

于 2012-08-28T19:51:47.713 回答
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);
于 2012-08-28T19:23:38.313 回答
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

于 2012-08-28T19:28:27.067 回答