更新未在表中反映的查询结果

时间:2013-12-26 06:44:20

标签: sql oracle

我有两张表test1test2。我需要的是,我想使用表test2中的数据更新表test1中的一列。我的问题是

 UPDATE test2 t2 
    SET t2.name = (SELECT t1.name 
                     FROM test1 t1 
                    WHERE t1.id = t2.mob)
  WHERE t2.mob IN (SELECT t1.id 
                     FROM test1 t1 
                    WHERE t1.id = t2.mob) 

它显示3 Rows updated,但它没有反映在我的表格中。我的reference。我的查询中是否有任何问题。或者我该怎么做。

enter image description here

3 个答案:

答案 0 :(得分:2)

使用merge语句会更容易:

/* test tables */

SQL> create table test1(id1, name1) as
  2    select level
  3         , dbms_random.string('l', 7)
  4    from dual
  5    connect by level <= 5;
Table created

SQL> create table test2(id1, name1) as
  2    select level
  3         , cast(null as varchar2(11))
  4    from dual
  5    connect by level <= 5;
Table created 

表的内容:

SQL> column name1 format a10;
SQL> select * from test1;

       ID1 NAME1
---------- ----------
         1 ouegwac
         2 bptytsz
         3 xwpnuqi
         4 jrbxeza
         5 hlckwvk

SQL> select * from test2;

       ID1 NAME1
---------- ----------
         1 NULL
         2 NULL
         3 NULL
         4 NULL
         5 NULL

使用test2.name1列中的数据更新test1.name1列:

SQL> merge into test2 t
  2  using test1 q
  3     on (q.id1 = t.id1)
  4  when matched then
  5    update set t.name1 = q.name1
  6  ;

5 rows merged

SQL> select * from test2;

       ID1 NAME1
---------- ----------
         1 ouegwac
         2 bptytsz
         3 xwpnuqi
         4 jrbxeza
         5 hlckwvk

答案 1 :(得分:1)

UPDATE 
(SELECT test2.name as t2, test1.name as t1
 FROM test2
 INNER JOIN test1
 ON test2.MOB= test1.ID

) t
SET t.t2= t.t1

答案 2 :(得分:0)

查询中的WHERE部分绝对没有必要,因为它始终评估为TRUE。因此,更新t2中所有行的正确答案是:

UPDATE test2 t2 
 SET t2.name = (SELECT t1.name 
                 FROM test1 t1 
                WHERE t1.id = t2.mob)

同样在PL / SQL Developer中,默认情况下不会自动提交事务。您必须通过按面板上的绿色箭头手动提交它。

enter image description here

相关问题