Oracle UPDATE问题

时间:2010-01-22 17:14:21

标签: oracle

下面描述的更新是否可以在一个UPDATE语句中完成?

我想通过加入Operators.name_id来更新Users.name_idUsers.name = Operators.op_name值。 Users.nameOperators.op_name都有unique

我知道下面描述的情况并不遵循“最佳实践”,但它是我正在尝试做的更简单的示例:即使用另一个连接表中的值更新字段。

Table: Users
user_id    name
----------------
34         Billy
43         Jimmy
50         Joe

Table:  Operators (before UPDATE)
op_id   op_name   user_id
-------------------------
12      Billy     35
35      Jimmy     46
33      Joe       99


Table:  Operators (after UPDATE)
op_id   op_name   name_id
-------------------------
12      Billy     34
35      Jimmy     43
33      Joe       50

2 个答案:

答案 0 :(得分:4)

UPDATE   operators o
SET      user_id = 
         (
         SELECT  u.user_id
         FROM    users u
         WHERE   o.op_name = u.name
         )
WHERE    o.op_name IN
         (
         SELECT  name
         FROM    users
         )

Oracle 10g中,效率更高:

MERGE
INTO    operators o
USING   users u
ON      (u.name = o.op_name)
WHEN MATCHED THEN
UPDATE
SET     user_id = u.user_id

答案 1 :(得分:3)

update (
       select oo.user_id, uu.user_id uu_id
         from operators oo
              join
              users uu on uu.name = oo.op_name
       )
   set user_id = uu_id

以下是完整的测试脚本(我正在使用my_usersmy_operators,以免弄乱您的数据。)

drop table my_users;
create table my_users (
                      user_id number(2),
                      name    varchar2(30) unique
                      )
;
insert into my_users (user_id, name)
  select 34, 'Billy' from dual union all
  select 43, 'Jimmy' from dual union all
  select 50, 'Joe'   from dual
;
drop table my_operators;
create table my_operators (
                          op_id   number(2),
                          op_name varchar2(30) unique,
                          user_id number(2)
                          )
;
insert into my_operators (op_id, op_name, user_id)
  select 12, 'Billy', 35 from dual union all
  select 35, 'Jimmy', 46 from dual union all
  select 33, 'Joe',   99 from dual
;
update (
       select oo.user_id, uu.user_id uu_id
         from my_operators oo
              join
              my_users uu on uu.name = oo.op_name
       )
   set user_id = uu_id
;
select * from my_operators;