简体   繁体   中英

delete multiple rows from different tables on oracle

I have a two table.One of them is student, the other one is salary.

Student table

  id  | name   | code | status
  1   | steven | 123  | 100
  2   | joe    | 678  | 200
  3   | paul   | 758  | 100

Salary table

 id  | code | status |  currency
  1   | 123  | 100    |  euro
  2   | 678  | 200    |  dolar
  3   | 758  | 520    |  yuan

I want to delete row1 from Student table and row 1 and 2 from Salary table because code and status fields are same.

I write that query

delete a,b Student as a , join Salary as b  
on a.code= b.code and a.status = b.status

but it is not working.I want to delete rows with one query.Do you have any idea?

Would something like this do? PL/SQL, though, not SQL.

Initial data sets:

SQL> select * from student;

        ID NAME         CODE     STATUS
---------- ------ ---------- ----------
         1 steven        123        100
         2 joe           678        200
         3 paul          758        100

SQL> select * from salary;

        ID       CODE     STATUS CURREN
---------- ---------- ---------- ------
         1        123        100 euro
         2        678        200 dollar
         3        758        520 yuan

Remove common (CODE, STATUS) combinations:

SQL> begin
  2    for cur_r in (select code, status from student
  3                  intersect
  4                  select code, status from salary
  5                 )
  6    loop
  7      delete from student where code = cur_r.code and status = cur_r.status;
  8      delete from salary  where code = cur_r.code and status = cur_r.status;
  9    end loop;
 10  end;
 11  /

PL/SQL procedure successfully completed.

Result:

SQL> select * from student;

        ID NAME         CODE     STATUS
---------- ------ ---------- ----------
         3 paul          758        100

SQL> select * from salary;

        ID       CODE     STATUS CURREN
---------- ---------- ---------- ------
         3        758        520 yuan

SQL>

You can use two statements to do so easily:

delete student s where exists(
select * from student stu inner join salary sal on stu.code=sal.code and stu.status=sal.status and stu.id=s.id);

delete salary sal where not exists (select code from student stu where stu.code=sal.code);

First one to delete all the students having same code and status in both tables and second is to delete all the rows from salary table where code doesn't exist in student table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM