oracle 兩表關聯的update操作

來源:互聯網
上載者:User

create table a(  no number notnull,  name varchar(10) notnull,  loc varchar(10) notnull);  

create table b(  no number notnull,  name varchar(10) notnull,  loc varchar(10) notnull);  

insert into a values(10, 'AAA', 'Aremak1');  

insert into a values(20, 'BBB', 'Aremak2');

insert into a values(30, 'CCC', 'Aremak3');

insert into b values(1, 'AAA', 'Bremak1');

insert into b values(2, 'BBB', 'Bremak2');

insert into b values(3, 'DDD', 'Bremak3');

SELECT * FROM a;

       ID NAME       LOC

---------- ---------- ----------

       10 AAA        Aremak1

       20 BBB        Aremak2

       30 CCC        Aremak3

SELECT * FROM b;

       ID NAME       LOC

---------- ---------- ----------

        1 AAA        Bremak1

        2 BBB        Bremak2

        3 DDD        Bremak3

更新b表,使name相同的id更新為a表的id

oracle下sql1

update b set id = select a.id from a where a.name=b.name);

上述語句更新的時候,因為name為‘DDD’記錄在a表中沒有,這行無法擷取資料,會把id設為null

       ID NAME       LOC

---------- ---------- ----------

       10 AAA        Bremak1

       20 BBB        Bremak2

          DDD        Bremak3

為了避免這個錯誤需要更改sql1為sql2

update b set id = select a.id from a where a.name=b.name) where exists select 1 from a where a.name=b.name);

       ID NAME       LOC

---------- ---------- ----------

       10 AAA        Bremak1

       20 BBB        Bremak2

        3 DDD        Bremak3


錯誤總結:

1.sql1 select a.id from 後面不能跟a,b) update b set id = select a.id from a,b where a.name=b.name);

會導致錯誤 single-row subquery returns more than one row


2.sql2 exists 後面的語句中也不能跟a,b select 1 from a,b where a.name=b.name,

會導致該exists語句無效,但是不報錯。











相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.