Delete with Left Join in Oracle 10g

前端 未结 5 1781
臣服心动
臣服心动 2020-12-05 19:33

I have the following code that works fine in MS SQL Server:

delete grp
from grp
left join my_data
on grp.id1 = my_data.id1
and grp.id2 = my_data.id2
and grp.         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 19:49

    Either Vincent's answer https://stackoverflow.com/a/3675205 does not work at all, or it does not work in Oracle 12c. That answer should be improved by specifying the lowest or highest version of Oracle where this works. The proof:

    SELECT * FROM v$version where banner like 'Oracle%';
    /*
    Oracle Database 12c Standard Edition Release 12.2.0.1.0 - 64bit Production
    */
    create table a (id int);
    create table b (id int);
    insert into a select 1 from dual union select 2 from dual;
    insert into b select 1 from dual union select 2 from dual union select 3 from dual;
    select * from a right join b on b.id = a.id;
    /*
    1   1
    2   2
    null    3
    */
    delete from (
      select b.*
      from b
      inner join a on a.id = b.id
    )    
    /*
    Error at Command Line : 7 Column : 13
    Error report -
    SQL Error: ORA-01752: cannot delete from view without exactly one key-preserved table
    01752. 00000 -  "cannot delete from view without exactly one key-preserved table"
    *Cause:    The deleted table had
               - no key-preserved tables,
               - more than one key-preserved table, or
               - the key-preserved table was an unmerged view.
    *Action:   Redefine the view or delete it from the underlying base tables.
    */
    
    delete from b
    where rowid in (
      select b.rowid
      from b
      inner join a on a.id = b.id
    )
    /*
    2 rows deleted.
    */
    select * from a right join b on b.id = a.id
    /*
    null  3
    */
    
    drop table a;
    drop table b;
    

    Bottom line is, use WHERE ROWID IN () at least in 12c.

提交回复
热议问题