简体   繁体   中英

How do I delete a record in a table which has a primary key referenced in another table as foreign key?

In my database, I have a table say "employee" which has a primary key attribute "employee_id" and another attribute "salary". There is another table say "employee_qualification" which has a foreign key attribute "employee_id". So, how can I delete all the records from "employee" and "employee_qualifications" with salary=10000?

This doesn't seem to work.

DELETE FROM employee WHERE employee.salary=10000;

You can execute two statements.

DELETE FROM employee_qualifications WHERE employee_qualifications.employee_id in (SELECT employee_id FROM employee WHERE employee.salary=10000)
DELETE FROM employee WHERE employee.salary=10000

While this will work, it could leave some orphaned records in the employee_qualifications table. The below option will clean the orphaned records.

DELETE FROM employee WHERE employee.salary=10000
DELETE FROM employee_qualifications WHERE employee_qualifications.employee_id Not in (SELECT employee_id FROM employee)

MySQL allows deletes from multiple tables at the same time. So you can do:

DELETE e, eq
    FROM employee e JOIN
         employee_qualitifications eq
    WHERE e.employee_id = eq.employee_id AND
          e.salary = 10000;

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