[英]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".在我的数据库中,我有一个表,上面写着“employee”,它有一个主键属性“employee_id”和另一个属性“salary”。 There is another table say "employee_qualification" which has a foreign key attribute "employee_id".
还有一个表说“employee_qualification”,它有一个外键属性“employee_id”。 So, how can I delete all the records from "employee" and "employee_qualifications" with salary=10000?
那么,如何从“employee”和“employee_qualifications”中删除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.虽然这会起作用,但它可能会在employee_qualifications 表中留下一些孤立的记录。 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. MySQL 允许同时从多个表中删除。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.